DataAnnotation 验证属性的 Int 或 Number 数据类型

发布于 2024-10-14 21:01:15 字数 598 浏览 7 评论 0原文

在我的 MVC3 项目中,我存储了 football/soccer/hockey/... 体育比赛的得分预测。因此,我的预测类的属性之一如下所示:

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

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

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

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:

[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, int in 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

洛阳烟雨空心柳 2024-10-21 21:01:15

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

对于整数

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

,对于浮点

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

,对于双精度

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

For any number validation you have to use different a 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")]
怪我入戏太深 2024-10-21 21:01:15

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

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


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

希望有帮助:D

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

晨光如昨 2024-10-21 21:01:15

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

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

Use regex in data annotation

[RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
public int MaxJsonLength { get; set; }
掩耳倾听 2024-10-21 21:01:15
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;
    }
}
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;
    }
}
倾城°AllureLove 2024-10-21 21:01:15

尝试这个属性:

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

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

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

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;
        }
    );
}
我早已燃尽 2024-10-21 21:01:15

通过将属性设置为视图模型中的字符串,我能够绕过所有框架消息。

[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 string HomeTeamPrediction { get; set; }

然后我需要在 get 方法

viewModel.HomeTeamPrediction = databaseModel.HomeTeamPrediction.ToString();

和 post 方法中进行一些转换:

databaseModel.HomeTeamPrediction = int.Parse(viewModel.HomeTeamPrediction);

这在使用 range 属性时效果最好,否则需要一些额外的验证来确保该值是数字。

您还可以通过将范围内的数字更改为正确的类型来指定数字的类型:

[Range(0, 10000000F, ErrorMessageResourceType = typeof(GauErrorMessages), ErrorMessageResourceName = nameof(GauErrorMessages.MoneyRange))]

I was able to bypass all the framework messages by making the property a string in my view model.

[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 string HomeTeamPrediction { get; set; }

Then I need to do some conversion in my get method:

viewModel.HomeTeamPrediction = databaseModel.HomeTeamPrediction.ToString();

and post method:

databaseModel.HomeTeamPrediction = int.Parse(viewModel.HomeTeamPrediction);

This works best when using the range attribute, otherwise some additional validation would be needed to make sure the value is a number.

You can also specify the type of number by changing the numbers in the range to the correct type:

[Range(0, 10000000F, ErrorMessageResourceType = typeof(GauErrorMessages), ErrorMessageResourceName = nameof(GauErrorMessages.MoneyRange))]
德意的啸 2024-10-21 21:01:15

您可以编写自定义验证属性:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class Numeric : ValidationAttribute
{
    public Numeric(string errorMessage) : base(errorMessage)
    {
    }

    /// <summary>
    /// Check if given value is numeric
    /// </summary>
    /// <param name="value">The input value</param>
    /// <returns>True if value is numeric</returns>
    public override bool IsValid(object value)
    {
        return decimal.TryParse(value?.ToString(), out _);
    }
}

然后您可以在您的属性上使用以下注释:

[Numeric("Please fill in a valid number.")]
public int NumberOfBooks { get; set; }

You can write a custom validation attribute:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class Numeric : ValidationAttribute
{
    public Numeric(string errorMessage) : base(errorMessage)
    {
    }

    /// <summary>
    /// Check if given value is numeric
    /// </summary>
    /// <param name="value">The input value</param>
    /// <returns>True if value is numeric</returns>
    public override bool IsValid(object value)
    {
        return decimal.TryParse(value?.ToString(), out _);
    }
}

On your property you can then use the following annotation:

[Numeric("Please fill in a valid number.")]
public int NumberOfBooks { get; set; }
一杯敬自由 2024-10-21 21:01:15

近十年过去了,但该问题在 Asp.Net Core 2.2 中仍然存在。

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

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

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

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

<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>
坐在坟头思考人生 2024-10-21 21:01:15

ASP.NET Core 3.1

这是我对该功能的实现,它在服务器端工作,并且与 jquery 验证一起使用,就像任何其他属性一样,带有自定义错误消息,不引人注意:

属性:< /strong>

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

客户端逻辑:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

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

最后是用法:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }

ASP.NET Core 3.1

This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

The attribute:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

Client side logic:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

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

And finally the Usage:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }
雪花飘飘的天空 2024-10-21 21:01:15

另一个简单的解决方案将插入内置框架,包括通过扩展 System.ComponentModel.DataAnnotations.RegularExpressionAttribute 进行客户端验证。
使用几个常量作为允许 0+ 的正则表达式,或者使用 bool 标志允许 1+。

namespace MyCustomNamespace.MyCustomAttributes {
    public class ValidPositiveIntegerAttribute : System.ComponentModel.DataAnnotations.RegularExpressionAttribute {
         
        private const string defaultErrorMessage = "* invalid integer value";
        private const string onePlusRegex = @"(^[1-9]*\.?[0-9]+$)";
        private const string zeroPlusRegex = @"(^[0-9]*\.?[0-9]+$)";     
            
        public ValidPositiveIntegerAttribute(string errorMessage, bool allowZero=false) : base(allowZero ? zeroPlusRegex : onePlusRegex) {
            this.ErrorMessage = errorMessage ?? defaultErrorMessage;
        }
        public ValidPositiveIntegerAttribute(bool allowZero = false) : base(allowZero ? zeroPlusRegex : onePlusRegex) {
            this.ErrorMessage = defaultErrorMessage;
        }       
    }
}

然后在模型上,您只需添加属性(确保您有可用于您创建的属性的命名空间:

[ValidPositiveInteger]
public int? HomeTeamPrediction { get; set; }

或允许零

[ValidPositiveInteger(true)]
public int? HomeTeamPrediction { get; set; }

Another simple solution that will plug into the built in framework, including client side validation by extending the System.ComponentModel.DataAnnotations.RegularExpressionAttribute.
Use a couple of constansts for the regular expressions for allowing 0+, or allow 1+ with a bool flag.

namespace MyCustomNamespace.MyCustomAttributes {
    public class ValidPositiveIntegerAttribute : System.ComponentModel.DataAnnotations.RegularExpressionAttribute {
         
        private const string defaultErrorMessage = "* invalid integer value";
        private const string onePlusRegex = @"(^[1-9]*\.?[0-9]+$)";
        private const string zeroPlusRegex = @"(^[0-9]*\.?[0-9]+$)";     
            
        public ValidPositiveIntegerAttribute(string errorMessage, bool allowZero=false) : base(allowZero ? zeroPlusRegex : onePlusRegex) {
            this.ErrorMessage = errorMessage ?? defaultErrorMessage;
        }
        public ValidPositiveIntegerAttribute(bool allowZero = false) : base(allowZero ? zeroPlusRegex : onePlusRegex) {
            this.ErrorMessage = defaultErrorMessage;
        }       
    }
}

And then on the model you just add the attribute(make sure you have the namespace availiable for the attribute you create:

[ValidPositiveInteger]
public int? HomeTeamPrediction { get; set; }

or to allow Zero

[ValidPositiveInteger(true)]
public int? HomeTeamPrediction { get; set; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文