Search code examples
asp.net-mvc-4remote-validation

MVC Remote Validation Error kept after change


I'm having trouble with my remote validation checking a second time after an invalid email has been given. I can't figure out why it's not removing the error after its no longer invalid.

Here is my Model:

[Required(ErrorMessage = "An email is required")]
[StringLength(150, MinimumLength = 4)]
[Display(Name = "Email")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "Invalid Email")]
[Remote("doesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "This email has already registered. Please use a different email")]
public virtual string strEmail { get; set; }

My View:

<ul>
        <li class="editor-label">@Html.LabelFor(m => m.strEmail)</li>
        <li class="editor-field">@Html.TextBoxFor(m => m.strEmail)</li>
        <li class="error">@Html.ValidationMessageFor(m => m.strEmail)</li>
</ul>

My Controller:

[HttpPost]
public JsonResult doesEmailExist(string strEmail)
    {

        var user = db.t_user.FirstOrDefault(i => i.email == strEmail);
        if (user == null)
            return Json(null);
        else
            return Json(false);

    }

Why is the remote validation not correcting itself going from an invalid entry to a valid entry?


Solution

  • Your JsonReturn need to return true (not null) if no existing email exists. Note this really should be a GET

    [HttpGet]
    public JsonResult doesEmailExist(string strEmail)
    {
      var user = db.t_user.FirstOrDefault(i => i.email == strEmail);
      if (user == null)
        return Json(true, JsonRequestBehavior.AllowGet); // change this
      else
         return Json(false, JsonRequestBehavior.AllowGet);
    
    }
    

    or

     bool exists = db.t_user.Any(i => i.email == strEmail)
     return Json(!exists, JsonRequestBehavior.AllowGet);
    

    Note also you can use [EmailAddress] in lieu of your [RegularExpression] attribute