Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable unobtrusive validation on an ASP.NET MVC form

I have two forms on a page. I want the first form to use unobtrusive validation, as it's since automatically generated by ASP.NET MVC Framework. There is a second form, however, which I wrote manually, that should not use unobtrusive validation.

Here's some code:

@using (Html.BeginForm("Add", "Contacts", FormMethod.Post, new { id = "AddForm" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Datos Contacto</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ContactDepartmentID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.ContactDepartmentID, (List<SelectListItem>)ViewBag.ContactDepartments)
            @Html.ValidationMessageFor(model => model.ContactDepartmentID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Sex)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Sex, (List<SelectListItem>)ViewBag.Sexs)
            @Html.ValidationMessageFor(model => model.Sex)
        </div>
    </fieldset>
    <br />
    @Html.HiddenFor(model => model.SerializedEmails, new { data_bind = "value: ko.toJSON($root.emails())" })
    @Html.HiddenFor(model => model.SerializedPhones, new { data_bind = "value: ko.toJSON($root.phones())" })
}
<form id="phoneForm" >
<fieldset>
    <legend>Teléfonos</legend>
    <table class="table">
        <tbody data-bind="foreach: phones">
            <tr>
                <th>
                    Celular?
                </th>
                <th>
                    Phone
                </th>
                <th>
                    Extension
                </th>
                <th>
                </th>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" data-bind="checked: isMobile" />
                </td>
                <td>
                    <input class="phone" data-bind='value: phone'/>
                </td>
                <td>
                    <input type="text" class="extension" data-bind='value: phoneExtension, enable: !isMobile() ' />
                </td>
                <td>
                    <a href='#' data-bind='click: $root.removePhone'>Delete</a>
                </td>
            </tr>
        </tbody>
    </table>
    <a href='#' data-bind='click: $root.addPhone'>Agregar teléfono</a>
</fieldset>
</form>
<p>
    <button onclick="Submit();" type="button" class="btn btn-primary" data-bind='enable: phones().length > 0 || emails().length > 0'>
        Create</button>
</p>

JS:

function Submit()
{      
  var valid = $('#AddForm').valid();     
  var valid2 =  $('#phoneForm').valid();     
}

jQuery.validator.addClassRules("phone", {
  required: true
});

As a side note: When I remove the unobtrusive validation from the page, the second form validates, but the first does not. If I use unobtrusive validation the first form validates, but the second form does not.

I know I can do the whole validation on the client side—and, if that's the only way, I will do it. I was thinking about a way to continue using unobtrusive validation, but allowing it to be conditionally disabled using e.g. custom attributes.

like image 919
Sanchitos Avatar asked Aug 09 '13 16:08

Sanchitos


People also ask

Which method is used to enable or disable client-side validation in ASP.NET MVC?

To disable client-side validation, set the page's ClientTarget property to 'Downlevel' ('Uplevel' forces client-side validation). Alternatively, you can set an individual validator control's EnableClientScript property to 'false' to disable client-side validation for that specific control.

What is unobtrusive validation in ASP.NET MVC?

Unobtrusive Validation allows us to take the already-existing validation attributes and use them client-side to make our user experience that much nicer. The Unobtrusive script files are included automatically with new MVC projects in Visual Studio, but if you don't have them you can get them from NuGet.

What is unobtrusive validation in asp net?

Unobtrusive validation makes use of jQuery library and data-* attributes of HTML5 to validate data entered in the web form controls. Unobtrusive validations can be enabled in the web. config file, Global. asax or individual Web Form code-behind.

Where can client-side validation be deactivated?

You can simply disable client side validation in the Razor view prior to render the field and re-enable client side validation after the field has been rendered.


2 Answers

You can disable the unobtrusive validation from within the razor code via this Html Helper property:

HtmlHelper.ClientValidationEnabled = false;

That way you can have unobtrusive validation on and off for different forms according to this setting in their particular view/partial view.

like image 156
S__ Avatar answered Nov 15 '22 06:11

S__


You can mark the elements or find it all the input of the second form and remove the rules, this sample is for remove all rules of some controls in the form, this cause according with the user selected some options, the values required will be others. for this reason i store the rules to restore it later.

///Remove rules
$("input.rO,textarea.rO").each(function () {
   try
   {
      var rule = $(this).rules();
      if (rule) {
         $(this).data("rule", rule);
         $(this).rules("remove");
     }
  }
  catch(err){}
 });
 ///Restore rules
 $("input.rO.om" + v + ",textarea.rO.om"+v).each(function () {
      try
      {
        var rule = $(this).data("rule");
        if (rule)
           $(this).rules("add", rule);
      }
      catch(err){}
    });
like image 35
Byron Avatar answered Nov 15 '22 05:11

Byron