Remote validation in mvc C#

How to: Implement Remote Validation from a Client in MVC4

A remote server calls in order to validate a form field without posting the entire form to the server.
Model:
public class ForgotPasswordModel
{
    [Remote("DoesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Your Email address was not found. Please try again.")]
    [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$", ErrorMessage = "Your email address is not in a valid format. Example of correct format: [email protected]")]
    [StringLength(100)]
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string EmailAddress { get; set; }
}


So you want to add AdditionalFields in remote validation is very is to add other fields.
Like
[Remote("DoesEmailExist", "Account", AdditionalFields = "id", HttpMethod = "POST", ErrorMessage = "Your Email address was not found. Please try again.")]

Controller:
[AllowAnonymous]
[HttpPost]
public JsonResult DoesEmailExist(ForgotPasswordModel forgot)
{
    // return true or false, if email exist or not
    return Json(false, JsonRequestBehavior.AllowGet);
}

[AllowAnonymous]
[HttpPost]
public ActionResult ForgotPassword(ForgotPasswordModel forgotPassword)
{
    if (ModelState.IsValid)
    {
       // do you work
    }
    return View(forgotPassword);
}

View:
@model AppName.Models.ForgotPasswordModel
@{
    ViewBag.Title = "Forgot Password";
}
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.EmailAddress)
    @Html.TextBoxFor(model => model.EmailAddress)
    @Html.ValidationMessageFor(model => model.EmailAddress)
    <input type="hidden" name="InitialEmail" value="[email protected]" />
    <input type="submit" value="Submit"/>
}

Remote validation in MVC 4 doesn't work why?

In Web.config file.
The appSettings element contains the following keys to enable client validation and enable unobtrusive JavaScript validation.
<appSettings>
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

If you have wrong jquery url mapping. Make sure src @Url.Content("~/Scripts/jquery.validate.js") is valid.
Remote validation in mvc C# Remote validation in mvc C# Reviewed by Bhaumik Patel on 8:59 PM Rating: 5