简体   繁体   English

MVC模型验证不引人注目

[英]MVC Model Validation Unobtrusive

I'm using the jquery unobtrusive method of validating my models in the UI. 我正在使用jquery不干扰方法在UI中验证我的模型。 I have a numeric field in a model that I want to validate as a number. 我在模型中有一个数字字段,需要验证为数字。 Out of the box, it almost works correctly. 开箱即用,它几乎可以正常工作。 It fails on the client side when validating .33 versus 0.33. 验证.33与0.33时,它在客户端失败。 I know that I can change regex in the jquery validation plugin, but that doesn't seem to be ideal. 我知道我可以在jquery验证插件中更改正则表达式,但这似乎并不理想。

So, to try to fix the issue without modding the plugin itself, I created the following validation attribute: 因此,为了尝试解决此问题而不修改插件本身,我创建了以下验证属性:

public class DecimalValidator : System.ComponentModel.DataAnnotations.ValidationAttribute, System.Web.Mvc.IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        decimal val = 0;
        ValidationResult ret = new ValidationResult("Must be a valid decimal");

        if (decimal.TryParse(value.ToString(), out val) )
            return ValidationResult.Success;
        else
            return ret;
    }


    #region IClientValidatable Members

    public System.Collections.Generic.IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
    {
        List<System.Web.Mvc.ModelClientValidationRule> ret = new List<System.Web.Mvc.ModelClientValidationRule>();

        System.Web.Mvc.ModelClientValidationRule validDecimalRule = new System.Web.Mvc.ModelClientValidationRule
        {
            ErrorMessage = "Please enter a valid decimal.",
            ValidationType = "decimal"
        };

        ret.Add(validDecimalRule);

        return ret;
    }

    #endregion
}

And applied it like so: 并像这样应用它:

    /// <summary>
    /// The price per unit.
    /// </summary>
    [Range(0, double.MaxValue)]
    [Display(Name = "Price")]
    [DecimalValidator]
    public decimal UnitPrice { get; set; }

The problem is that the html still renders with data-val-number="The field Price must be a number." 问题是html仍然使用data-val-number =“字段Price必须是数字。” in addition to the new one, data-val-decimal="Please enter a valid decimal." 除了新的之外,data-val-decimal =“请输入一个有效的十进制。”

How do I keep the default validation attributes from being rendered? 如何保持默认的验证属性不被渲染?

I believe the [Range(0, double.MaxValue)] is forcing it load the number validation. 我相信[Range(0, double.MaxValue)]强迫它加载数字验证。 Try adding that into your custom validator and removing it from your field decorators. 尝试将其添加到自定义验证器中,然后将其从字段装饰器中删除。

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    decimal val = 0;
    ValidationResult ret = new ValidationResult("Must be a valid decimal");
    ValidationResult rangeRet = new ValidationResult(String.Format("Number must be between 0 and {0}", double.MaxValue.ToString());

    if (decimal.TryParse(value.ToString(), out val) )
        return ValidationResult.Success;
    else if (value < 0 || value > double.MaxValue)
        return rangeRet;
    else
        return ret;
}

我发现答案是使用$ .extend用允许.33和0.33的正则表达式替换插件中的数字验证

Why are you creating a custom validator? 为什么要创建自定义验证器? MVC will validate for you by default. 默认情况下,MVC将为您验证。 If you make your type nullable (decimal?) then MVC will set UnitPrice to null if a non-decimal is entered, as well as make your model state invalid if it violates any other validation you are doing. 如果将类型设为可空(十进制?),则MVC将在输入非十进制的情况下将UnitPrice设置为null,并且如果模型状态违反您正在执行的任何其他验证,则将使模型状态无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM