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)
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
小智 15
在数据注释中使用正则表达式
[RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
public int MaxJsonLength { get; set; }
Run Code Online (Sandbox Code Playgroud)
试试这个属性:
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)
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)