MVC自定义客户端验证

时间:2014-02-10 08:56:58

标签: asp.net-mvc-4 c#-4.0 jquery-validate unobtrusive-validation

我有以下自定义必需属性代码:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class AddressRequiredAttribute : RequiredAttribute, IClientValidatable
{
    /// <summary>
    /// The _property name
    /// </summary>
    private string _propertyName;

    /// <summary>
    /// Initializes a new instance of the <see cref="AddressRequiredAttribute"/> class.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    public AddressRequiredAttribute(string propertyName)
        : base()
    {
        _propertyName = propertyName;
    }

    /// <summary>
    /// Checks that the value of the required data field is not empty.
    /// </summary>
    /// <param name="value">The data field value to validate.</param>
    /// <returns>
    /// true if validation is successful; otherwise, false.
    /// </returns>
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        if (context.ObjectType.BaseType == typeof(AddressModel))
        {
            PropertyInfo property = context.ObjectType.GetProperty(_propertyName);
            if (property != null && (bool)property.GetValue(context.ObjectInstance))
            {
                return base.IsValid(value, context);
            }
        }

        return ValidationResult.Success;
    }

    /// <summary>
    /// When implemented in a class, returns client validation rules for that class.
    /// </summary>
    /// <param name="metadata">The model metadata.</param>
    /// <param name="context">The controller context.</param>
    /// <returns>
    /// The client validation rules for this validator.
    /// </returns>
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string errorMessage = this.ErrorMessage;

        // Get the specific error message if set, otherwise the default
        if (string.IsNullOrEmpty(errorMessage) && metadata != null)
        {
            errorMessage = FormatErrorMessage(metadata.GetDisplayName());
        }

        var clientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = errorMessage,
            ValidationType = "requiredaddress"
        };

        return new[] { clientValidationRule };
    }

以及在window.load上运行的客户端验证的以下jquery:

$.validator.addMethod('requiredaddress', function (value, element, params) {
    return value != '';
}, '');

$.validator.unobtrusive.adapters.add('requiredaddress', {}, function (options) {
    options.rules['requiredaddress'] = true;
    options.messages['requiredaddress'] = options.message;
});

然而,客户端没有启动所以我得到正常的客户端验证工作,然后表单将提交但回发后返回自定义错误。我看过的所有例子都说我的代码应该是正确的,所以我不确定这里有什么问题。

任何人都可以看到任何明显我在这里做错的事,谢谢

1 个答案:

答案 0 :(得分:2)

我做了类似的事情,发现如果我将代码放在document.ready window.load上,那就不行了。最后,我使用了jquery验证脚本之后放置的以下代码:

(function ($) {
    $.validator.addMethod('requiredaddress', function (value, element, params) {
        return value != '';
    }, 'Clientside Should Not Postback');

    // i think you should be able to use this as your adapter
    $.validator.unobtrusive.adapters.addBool('requiredaddress');
})(jQuery);