Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Razor Validation Errors showing on page load when no data has been posted

I'm messing around with data annotations. When I click on a link to go to a page, the validation messages are being displayed, but I would like to have the validation messages not show unless data has been posted.

View:

@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" })
@Html.ValidationSummary(true, "Registration Failed. Check your credentials")
@Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.")

Model:

[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email Address: ")]
public string EmailAddress { get; set; }

Controller:

[HttpGet]
        public ActionResult AddUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(UserCreateViewModel user)
        {
            if (ModelState.IsValid)
            {
                var success = UserRepository.AddUser(user);

                if (success)
                {
                    return View("Success");
                }
            }

            return View("AddUser");
        }

Like I said, my problem occurs on page load of the AddUser view. When I click on the link to view the AddUser page, validation messages are showing after it loads, yet at this point no data has been posted and the model is empty.

like image 564
allencoded Avatar asked Jan 22 '14 23:01

allencoded


People also ask

Can we do validation in MVC using data annotations?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.

Which HtmlHelper is used to show the validation messages?

ValidationMessage(HtmlHelper, String) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

Which namespace is required for validating the input data in MVC?

DataAnnotations namespace. These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users.

What is input validation in Razor pages?

Validating User Input in Razor Pages. When you allow users to provide values that you then process, you need to ensure that the incoming values are of the expected data type, that they are within the permitted range and that required values are present. This process is known as input validation.

How do I display validation error messages in MVC?

You can see how a validation error message appears in the picture below. You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary ()  method returns an unordered list ( ul element) of validation messages that are in the ModelStateDictionary  object.

How to disable validation messages on initial page load?

By adding CSS to display none as that particular class's value, you'll no longer see the validation messages on initial page load. The validation messages will still display normally after the particular input element has been touched. Show activity on this post.

What happens if there are any validation errors on a page?

If there are any validation errors, you skip normal page processing. For example, if the purpose of the page is to update a database, you don't do that until all validation errors have been fixed. If there are validation errors, display error messages in the page's markup by using Html.ValidationSummary or Html.ValidationMessage, or both.


4 Answers

You can clear model state after binding user:

ModelState.Clear(); 

This happens because ModelBinder will set ModelState on binding. In every action that binds a model and returns a view with the same model you will have this problem.

[HttpPost] public ActionResult AddUser(UserCreateViewModel user) {     if (ModelState.IsValid)     {         var success = UserRepository.AddUser(user);          if (success)         {             return View("Success");         }     }      ModelState.Clear(); // <-------     return View("AddUser"); } 
like image 131
Renan Araújo Avatar answered Sep 30 '22 17:09

Renan Araújo


Set the validation style to:

.validation-summary-valid { display:none; } 

So by default it's hidden. An error will trigger it to display.

like image 25
mnsr Avatar answered Sep 30 '22 17:09

mnsr


.field-validation-valid {
  display: none;
}

Whenever the validation triggers on page load, this ".field-validation-valid" value is automatically added to the class attribute of the triggered input element.

By adding CSS to display none as that particular class's value, you'll no longer see the validation messages on initial page load.

The validation messages will still display normally after the particular input element has been touched.

like image 33
Jimmy Shaw Avatar answered Sep 30 '22 17:09

Jimmy Shaw


$('.field-validation-error').html("");

like image 26
Nitin Avatar answered Sep 30 '22 17:09

Nitin