Note that there are some explanatory texts on larger screens.

plurals
  1. PORequired validator always returns false
    text
    copied!<p>I have an EF Code First model which I'm editing via an MVC page, with a particular field that always returns false with the [Required] data annotation. If I hard set a value right before validating, it still fails.</p> <p>It's for a User object, of which I can configure if I'm using a username or email address as the 'username' property.</p> <p>The model:</p> <pre><code>public class User { [DisplayName("User Id")] public int Id { get; set; } [Required(ErrorMessage="Username is required")] public string Username { get; set; } [UIHint("EmailAddress")] [Required(ErrorMessage = "Email is required")] [EmailAddress] public string Email { get; set; } } </code></pre> <p>In my view, I'm only drawing the <code>Username</code> editor if it's required:</p> <pre><code>@if (@ViewBag.LoginMethod == "username") { @Html.LabelFor(m =&gt; m.Username) @Html.TextBoxFor(m =&gt; m.Username, new { autocomplete = "off" }) @Html.ValidationMessageFor(m =&gt; m.Username) } @Html.LabelFor(m =&gt; m.Email) @Html.TextBoxFor(m =&gt; m.Email, new { autocomplete = "off" }) @Html.ValidationMessageFor(m =&gt; m.Email) </code></pre> <p>My controller:</p> <pre><code>[HttpPost] public ActionResult Create(UserModel viewModel) { ViewBag.LoginMethod = this.loginMethod.ToString(); var user = new User(); if (this.loginMethod == LoginMethods.Username) user.Username = viewModel.User.Username; else user.Username = viewModel.User.Email; user.Email = viewModel.User.Email; user.FirstName = viewModel.User.FirstName; user.LastName = viewModel.User.LastName; user.Username = "TEST"; if (TryValidateModel(user) == false) { this.FlashError("Validation Errors!"); return View(viewModel); } throw new Exception("here"); } </code></pre> <p>As you can see, I'm setting the User.Username property, based on the login method. For the sake of testing, I'm setting it to "TEST", right before validation. The Username Required validation returns false, and I end up back in my view. I never get to the exception.</p> <p>I have managed to make it work correctly, by rendering the Username editor on the page no matter what. As I have client side validation enabled, I can't submit the form without entering a value, and it works - even though the Username value is still "TEST" once validated.</p> <p>I'm beginning to think <code>TryValidateModel</code> isn't the right function. Using <code>ModelState.IsValid</code> yields the same result - an incorrect Required fail.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload