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

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

现在,我还需要更改数据类型的错误消息,在我的例子中是 int。有一些默认的使用-“字段 HomeTeam預必须是一个数字。”.需要找到更改此错误消息的方法。这个验证消息似乎也需要预测远程验证。

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

276592 次浏览

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

希望能有所帮助

试试这个属性:

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

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

为了整数

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

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

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

差不多十年过去了,但这个问题仍然适用于 Asp.Net Core 2.2。

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

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

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

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

邮寄方法:

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

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

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

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

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

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