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

问题描述 投票:0回答:9

在我的 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
枚举中的普通数字。

asp.net-mvc asp.net-mvc-3 data-annotations
9个回答
252
投票

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

对于整数

[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")]

91
投票

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

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


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

希望有帮助:D


25
投票

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

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

9
投票
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;
    }
}

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

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

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

4
投票

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

[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();

及邮寄方式:

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

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

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

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

3
投票

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

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

1
投票

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

我通过将

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

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

1
投票

ASP.NET Core 3.1

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

属性:

  [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; }
© www.soinside.com 2019 - 2024. All rights reserved.