asp.net-mvc DataAnnotation 验证属性的 Int 或 Number DataType

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4816822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:48:19  来源:igfitidea点击:

Int or Number DataType for DataAnnotation validation attribute

asp.net-mvcasp.net-mvc-3data-annotations

提问by Antonin Jelinek

On my MVC3 project, I store score prediction for football/soccer/hockey/... sport game. So one of properties of my prediction class looks like this:

在我的 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; }

Now, I need also change error message for a data type, intin my case. There is some default one used - "The field HomeTeamPrediction must be a number.". Need to find a way how to change this error message. This validation message also seem to take prediction for Remote validation one.

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

I've tried [DataType]attribute but this does not seem to be plain number in system.componentmodel.dataannotations.datatypeenumeration.

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

回答by Dilip0165

For any number validation you have to use different different range validation as per your requirements :

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

For Integer

对于整数

[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]

for float

浮动

[Range(0, float.MaxValue, ErrorMessage = "Please enter valid float Number")]

for double

双人

[Range(0, double.MaxValue, ErrorMessage = "Please enter valid doubleNumber")]

回答by Goran ?uri

Try one of these regular expressions:

尝试以下正则表达式之一:

// for numbers that need to start with a zero
[RegularExpression("([0-9]+)")] 


// for numbers that begin from 1
[RegularExpression("([1-9][0-9]*)")] 

hope it helps :D

希望它有帮助:D

回答by Sathish

Use regex in data annotation

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

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

回答by Stefan Turcanu

Try this attribute :

试试这个属性:

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;
    }
}

And also you must register the attribute in the validator plugin:

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

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

回答by stuartdotnet

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;
    }
}

回答by Laz Ziya

almost a decade passed but the issue still valid with Asp.Net Core 2.2 as well.

将近十年过去了,但这个问题在 Asp.Net Core 2.2 中仍然有效。

I managed it by adding data-val-numberto the input field the use localization on the message:

我通过将data-val-number消息的使用本地化添加到输入字段来管理它:

<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>