Display one error message for 3 text fields with mvc 4 razor motor

I am now checking the fax number in which I need to display only one error message for all three text fields. As a resume

This seems like a bit picky / stupid of business requirements, as there are 3 text boxes, and all of them are necessary on their own, but if someone did, it would be nice.

In my model:

[Required(ErrorMessage = "Fax is Required...")] [RegularExpression("^[0-9]{3}$", ErrorMessage = "Not a valid fax #")] public string poc_fax_1 { get; set; } [Required(ErrorMessage = "Fax is Required...")] [RegularExpression("^[0-9]{3}$", ErrorMessage = "Not a valid fax #")] public string poc_fax_2 { get; set; } [Required(ErrorMessage = "Fax is Required...")] [RegularExpression("^[0-9]{4}$", ErrorMessage = "Not a valid fax #")] public string poc_fax_3 { get; set; } 

View:

 (@Html.TextBoxFor(model => model.poc_fax_1, new { @class = "input-mini", @maxlength=3 })) - @Html.ValidationMessageFor(m=>m.poc_fax_1) @Html.TextBoxFor(model => model.poc_fax_2, new { @class = "input-mini", @maxlength=3 }) - @Html.ValidationMessageFor(m=>m.poc_fax_2) @Html.TextBoxFor(model => model.poc_fax_3, new { @class = "input-mini", @maxlength=4 }) @Html.ValidationMessageFor(m=>m.poc_fax_3) 

enter image description here

Note. The image before I fixed only a numerical record and thus updated the question.

+4
source share
1 answer

Instead of using annotations for each part of the fax number, you can check the operation of the controller if the 3 fields together are valid.

Something like this: check your controller

 if (faxfield1 != null && faxfield2 != null && faxfield3 != null) { ModelState.AddModelError("FaxError", "Fax is not valid"); } 

Then use this in your view (once)

 @Html.ValidationMessage("FaxError") 

Note: this just shows how you can do it in a different way, you will have to use a different check c :)

+6
source

Source: https://habr.com/ru/post/1492847/


All Articles