Javascript – Disable client side validation for some fields in ASP.NET MVC

asp.netasp.net-mvcclient-side-validationjavascriptvalidation

How can I conditionally disable client-side validation of some fields ?

Here is the example of what I need to do:

  • user writes name and address and submits.
  • Both are validated both server and client side. If validation passes e-mail is send to given address and (name, address) pair is stored.
  • as a response same page is displayed (I don't want redirect!) this time with confirmation. User can retype their name and submit. In such case e-mail will be resend to the address that corresponds to given name.

It does not work because: client side validation will not pass when user clicks resent button on the second (confirmation screen). It would say that e-mail is required even if there is no field for it. How can I disable javascript validating email before the confirm page gets send to user ?

Example ASP.NET MVC page

<%if (Model.Confirm == false){ %>
    <% using (Html.BeginForm()) { %>
        Your email: <%: Html.EditorFor(m => m.Email) %>
        Your name: <%: Html.EditorFor(m => m.Name) %>
        <input type="submit" value="Send Email" />
    <% } %>
<%} else{ %>
    The e-mail was send! You can write your name and click button to resend it.
    <% using (Html.BeginForm()) { %>
        Your name: <%: Html.EditorFor(m => m.Name) %>
        <input type="submit" value="Resend me email again" />
    <% } %>
<% } %>

In the model both Email and Name are required field to enforce client side validation.

Example controller actions

 public ActionResult Index(){
     return new MyModel {Confirm = false;}
 }

 [HttpPost]
 public ActionResult Index(MyModel model){
     if(DataHelper.isKnown(model.Name)){
         //send e-mail to the address corresponding to name in database 
     }
     if(!ModelState.IsValid) {
         return View(model);
     }
     //Send e-mail to address in email
     //store pair name->email to database
     model.Confirm = true;
     return View(model);
 }

Best Answer

Just a simple solution for this, I will hide the email field for the second confirmation and preserve its value.

<%} else{ %>
    The e-mail was send! You can write your name and click button to resend it.
    <% using (Html.BeginForm()) { %>
        <%: Html.HiddenFor(m => m.Email) %>
        Your name: <%: Html.EditorFor(m => m.Name) %>
        <input type="submit" value="Resend me email again" />
    <% } %>
<% } %>