MVC3 Attribute validation question

萝らか妹 提交于 2019-12-06 08:28:33
Alexander Kahoun

What's happening to you now is the post validation is kicking in after the form has been submitted and determining that the decimal value cannot be null. Right now you are using a decimal type which is non-nullable. If you want this behavior and you want to see the validation before you submit the form then add the [Required] attribute to the property. However if you don't want this functionality and it can possibly be null, then change your type from decimal to decimal? or Nullable<decimal>.

Don't allow nulls and have the pre-submit validation:

[Display(Name = "Overflow Capacity")]
[RegularExpression(@"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
[Required]
public decimal OverFlowCapacity { get; set; }

Allow nulls and get rid of post-submit validation error:

[Display(Name = "Overflow Capacity")]
[RegularExpression(@"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
public decimal? OverFlowCapacity { get; set; }

Since you're not marking your decimal type as nullable, MVC doesn't know what to do with the empty field you're posting back. Try this if you want to allow nulls/empty fields:

public decimal? OverFlowCapacity { get; set; }

and try this if you want it to have a pre-submit validation message requiring the field to be filled in:

[Required]
public decimal OverFlowCapacity { get; set; }

Answers above explain Required error message quite well so i will just focus on second error message. i.e if you put 'abc' jquery tells you "Number Required". How does jquery know that this input should only accept number fields. The answer is; through unobtrusive attributes that are generated with form fields. If you inspect input field you will find something like

<input name="OverFlowCapacity" id="OverFlowCapacity" data-val-number="Number Required"..../>

so to override this default validation message you have to decorate your model with the attribute that does the exact same thing (number validation) and their you can override the validation message

[Numeric(ErrorMessage="override message")]
[Required(ErrorMessage="override Required message")]
public decimal OverFlowCapacity{get;set;}

I doubt Numeric attribute is present in DataAnnotation or mvc framework. you have to check into that. There are some useful attributes discussed and available here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!