【问题标题】:Clientside Validation in "Self Validate Model" in ASP.NET-MVC3ASP.NET-MVC3 中“自我验证模型”中的客户端验证
【发布时间】:2011-03-01 14:26:50
【问题描述】:

这是这个问题的后续问题:How does DataAnnotations really work in MVC? 有一个自定义验证示例,并提到了“自我验证模型”。这很有趣,但我不明白如何为其编写客户端验证。

我的模型对象能否实现 IClientValidateble 接口(或者它仅用于数据注解属性?),我想看看如何实现的示例。

编辑:据我了解,“自我验证模型”在不使用 DataAnnotations 的情况下工作,并在类中声明了我正在验证的属性的验证逻辑,而不是(必然)使用属性来验证某些东西。

我在自定义客户端验证中看到的所有示例都是关于实现 IClientValidatable 的数据注释属性

当我在我的类中声明我的验证逻辑时,我不使用属性来验证模型状态。

当我在实现 IValidatebleObject 接口的模型类的 Validate 方法中声明我的验证逻辑时,如何编写客户端验证?

我实际传递给视图的类能否实现 IClientValidatable 接口或类似的接口?

【问题讨论】:

    标签: c# .net asp.net-mvc-3 client-side-validation


    【解决方案1】:

    采取相同的答案:

    实现自我验证模型后,女巫是服务器端验证,您需要创建客户端验证部分,为此,只需创建以下 3 个步骤:

    • 实施
    • 实现一个 jQuery 验证方法
    • 实现一个不显眼的适配器

    附加到您的IClientValidateble

    public IEnumerable<ModelClientValidation> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelCLientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "greater"; // This is what the jQuery.Validation expects
        rule.ValidationParameters.Add("other", OtherPropertyName); // This is the 2nd parameter
    
        yield return rule;
    }
    

    然后您需要编写新的 jQuery Validator元数据适配器,将 jQuery.Validation 与您的代码链接起来,为该字段提供正确的 data- 属性(如果当然,UnobtrusiveJavaScriptEnabled 是真的)

    创建一个新的js 文件并附加到您的&lt;head&gt;,例如

    <script src="@Url.Content("~/Scripts/customValidation.js")" type="text/javascript"></script>
    

    并附加新的验证

    jQuery.validator.addMethod("greater", function(value, element, param) {
        // we need to take value and compare with the value in 2nd parameter that is hold in param
        return Date.parse(value) > Date.parse($(param).val());
    });
    

    然后我们编写适配器

    jQuery.validator.unobtrusive.adapters.add("greater", ["other"], function(options) {
        // pass the 'other' property value to the jQuery Validator
        options.rules["greater"] = "#" + options.param.other;
        // when this rule fails, show message that comes from ErrorMessage
        options.messages["greater"] = options.message;
    });
    

    您可以在创建新的 MVC3 Web 应用程序时在 AccountModel.cs 中查看此内容,它显示了实现 IClientValidatable 的此方法

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
    {
        private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
        private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
    
        public ValidatePasswordLengthAttribute()
            : base(_defaultErrorMessage)
        {
        }
    
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
                name, _minCharacters);
        }
    
        public override bool IsValid(object value)
        {
            string valueAsString = value as string;
            return (valueAsString != null && valueAsString.Length >= _minCharacters);
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[]{
                new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue)
            };
        }
    }
    #endregion
    

    【讨论】:

    • 这显然与之前的问题不同,因为他在这里询问是否可以在每个属性上使用 IClientValidatable WITHOUT (dataannotain) 属性!你的答案包含public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable,所以这显然不是一个正确的答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2012-01-05
    • 2012-03-06
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多