DataAnnotation验证属性的Int或Number DataType

Ant*_*nek 102 asp.net-mvc data-annotations asp.net-mvc-3

在我的MVC3项目中,我存储了足球/足球/曲棍球/ ...运动游戏的得分预测.所以我的预测类的一个属性看起来像这样:

[Range(0, 15, ErrorMessage = "Can only be between 0 .. 15")]
[StringLength(2, ErrorMessage = "Max 2 digits")]
[Remote("PredictionOK", "Predict", ErrorMessage = "Prediction can only be a number in range 0 .. 15")]
public int? HomeTeamPrediction { get; set; }
Run Code Online (Sandbox Code Playgroud)

现在,int在我的情况下,我还需要更改数据类型的错误消息.使用了一些默认值 - "HomeTeamPrediction字段必须是数字.".需要找到一种方法来更改此错误消息.此验证消息似乎也对远程验证进行了预测.

我已尝试过[DataType]属性但这在system.componentmodel.dataannotations.datatype枚举中似乎不是普通数字.

Dil*_*165 204

对于任何数字验证,您必须根据您的要求使用不同的范围验证:

对于整数

[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]
Run Code Online (Sandbox Code Playgroud)

浮动

[Range(0, float.MaxValue, ErrorMessage = "Please enter valid float Number")]
Run Code Online (Sandbox Code Playgroud)

为了双倍

[Range(0, double.MaxValue, ErrorMessage = "Please enter valid doubleNumber")]
Run Code Online (Sandbox Code Playgroud)

  • 在我的背景下,这对我不起作用.如果用户输入"asdf",[Range(typeof(decimal),"0","9999.99",ErrorMessage ="{0}的值必须介于{1}和{2}之间")]抛出异常.但是,如果我执行[Range(typeof(十进制),"0.1","9999.99",ErrorMessage ="{0}的值必须介于{1}和{2}"之间),错误消息将正常工作.0对0.1,没有意义.可能是错误? (4认同)
  • 此“整数”验证将非整数值视为有效(例如 0.3) (3认同)

Gor*_*uri 73

尝试正则表达式

[RegularExpression("([0-9]+)")]      // for 0-inf or 
[RegularExpression("([1-9][0-9]*)"] // for 1-inf
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助:D

  • 有没有更简单的方法?我希望有类似的东西:[数字(ErrorMessage ="此字段必须是数字")] (12认同)
  • 此正则表达式仅在属性类型为“int”时才有效,如果您使用“string”类型的属性,则正则表达式还将接受“a123”或任何其他至少在某处包含数字的字符串。要从头到尾验证数字,请对整数使用“^[0-9]+$”,对浮点数使用“^[0-9]*\.?[0-9]+$” (4认同)
  • 很不幸的是,不行.您始终可以编写自己的验证属性. (2认同)
  • 这是更好的解决方案,因为这涵盖了字符串.`int.MaxValue`只涵盖`2.147.483.647` (2认同)

小智 15

在数据注释中使用正则表达式

[RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
public int MaxJsonLength { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 这似乎在问题的上下文中工作正常,前提是该属性不是int,而是字符串. (2认同)
  • 此正则表达式仅在属性类型为“int”时才有效,如果您使用“string”类型的属性,则正则表达式还将接受“a123”或任何其他至少在某处包含数字的字符串。要从头到尾验证数字,请对整数使用“^[0-9]+$”,对浮点数使用“^[0-9]*\.?[0-9]+$” (2认同)

Ste*_*anu 6

试试这个属性:

public class NumericAttribute : ValidationAttribute, IClientValidatable {

    public override bool IsValid(object value) {
        return value.ToString().All(c => (c >= '0' && c <= '9') || c == '-' || c == ' ');
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "numeric"
        };
        yield return rule;
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您还必须在验证器插件中注册该属性:

if($.validator){
     $.validator.unobtrusive.adapters.add(
        'numeric', [], function (options) {
            options.rules['numeric'] = options.params;
            options.messages['numeric'] = options.message;
        }
    );
}
Run Code Online (Sandbox Code Playgroud)


stu*_*net 5

public class IsNumericAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            decimal val;
            var isNumeric = decimal.TryParse(value.ToString(), out val);

            if (!isNumeric)
            {                   
                return new ValidationResult("Must be numeric");                    
            }
        }

        return ValidationResult.Success;
    }
}
Run Code Online (Sandbox Code Playgroud)