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

4

29

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.

Saccharin answered 22/1, 2014 at 23:27 Comment(0)
V
14

Set the validation style to:

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

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

Voyeurism answered 23/1, 2014 at 0:27 Comment(3)
I was using a custom CSS file and had stop including the old Site.css reincluding this (which had your above fix) fixed my problem.Saccharin
Why on earth we need to do it manually. Why it's not handled by the framework itself. :-|Satterfield
This is most likely because the default Site.css was changed or is missing.Jurassic
C
50

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");
}
Cupro answered 18/3, 2016 at 17:37 Comment(4)
This is really helpful for me. I added ModelState.Clear() it's hide !!Sulcate
Good one buddy (y)Unwashed
It may be worth mentioning that this will only happen for GET requests if the action receives an object with data annotations (as opposed to having arguments corresponding to the properties that were needed or an entirely different class w/o data annotations)Hilel
it also seems to happen when the controller GET action has a parameter, with the same name as a property in the modelManuscript
V
14

Set the validation style to:

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

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

Voyeurism answered 23/1, 2014 at 0:27 Comment(3)
I was using a custom CSS file and had stop including the old Site.css reincluding this (which had your above fix) fixed my problem.Saccharin
Why on earth we need to do it manually. Why it's not handled by the framework itself. :-|Satterfield
This is most likely because the default Site.css was changed or is missing.Jurassic
A
2
.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.

Autogenous answered 16/11, 2017 at 19:55 Comment(3)
Care to explain how this answers OP's question?Bimonthly
This doesn't help the OP, but it helped me. Much appreciated!Insurrection
Me too. Thank you very muchPhagocytosis
J
1

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

Jenaejenda answered 20/4, 2017 at 8:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.