78

I'm using ASP .NET MVC 3 with Data Annotations and the jQuery validate plugin.

Is there a way to mark that a certain field (or certain data annotation) should only be validated server-side?

I have a phone number field with a masking plugin on it, and the regular expression validator goes crazy on the user's end. The regex is only a fail-safe (in case someone decides to hack the javascript validation), so I don't need it to run on the client side. But I'd still like the other validation to run client side.

7 Answers 7

109

I'm not sure if this solution works on MVC3. It surely works on MVC4:

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.

Example:

<div class="editor-field">
    @{ Html.EnableClientValidation(false); }
    @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" })
    @{ Html.EnableClientValidation(true); }
</div>

Here we disable client side validation for the BatchId field.

Also I have developed a little helper for this:

public static class YnnovaHtmlHelper
{
    public static ClientSideValidationDisabler BeginDisableClientSideValidation(this HtmlHelper html)
    {
        return new ClientSideValidationDisabler(html);
    }
}

public class ClientSideValidationDisabler : IDisposable
{
    private HtmlHelper _html;

    public ClientSideValidationDisabler(HtmlHelper html)
    {
        _html = html;
        _html.EnableClientValidation(false);
    }

    public void Dispose()
    {
        _html.EnableClientValidation(true);
        _html = null;
    }
}

You will use it as follow:

<div class="editor-field">
    @using (Html.BeginDisableClientSideValidation()) {
        @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" })
    }
</div>

If anyone has better solutions please let me know!

Hope this help.

Sign up to request clarification or add additional context in comments.

4 Comments

Nice, except it turns validation on even if it was off to begin with.
Surely it can be enhanced!
I got it working in a little more complicated situation, to remove an individual validation if the field has multiple validators by finding out what data attributes are added by that particular validation provider and setting them to an empty string. It's working so far. Thank you for the suggestion.
This is a very good solution due to the fact of the page loading less text in the source. It noticeably improved load times due to unnecessary validation text.
97

You can switch off client-side unobtrusive validation for a single field by adding a data-val='false' attribute:

@Html.TextBoxFor(m => m.BatchId, new { data_val = "false" })

This will override the data-val='true' attribute that MVC adds due to any System.ComponentModel.DataAnnotations attributes. The HTML element will still be decorated with other validation attributes (e.g. data-val-required) but they won't have any effect.

(Note the underscore in data_val above. MVC automatically converts underscores to hyphens in anonymous type properties, so data_val becomes data-val when rendering the HTML)

5 Comments

Unless I put the underscore, IIS gives me an exception. Compiler Error Message: CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
This worked like a charm and is the cleanest solution to this problem I have found yet.
This works great and is the cleanest solution. Thanks!
The @data_val does not render "data-val" in MVC 5.
It works like this: @Html.EditorFor(model=>model.Phone2, new { htmlAttributes = new { data_val_number = "Must be numeric" } })
21

MVC5 use jquery.validate

http://jqueryvalidation.org/rules/

If you want to remove validations in MVC5 client-Side you need to do the following:

Remove all validations on 'myinput'

$("#myinput").rules("remove");

Specific validations

$("#myinput").rules("remove", "min max" );

Listing the validations can help

$("#myinput").rules();

Then you will need to correct your Code Behind to validate manually your model or differently because ModelState.IsValid will be false. Using ModelState.Clear() and TryValidateModel can then be handy.

Edit:

Disabling the control also remove the validations.

$("#myinput").attr('disabled', disabledValue);

Comments

7

Assuming you use default unobtrusive validation, You could use some javascript to remove rules on client side. Take a look at Plugins/Validation/rules

Comments

7

To achieve this goal in the given scenario, we need to make two tweaks.

Client Side

To disable client side validation, we need to disable it by force.

@Html.EditorFor(model => model.Password, new { htmlAttributes = new {  @data_val = "false" , @class = "form-control"} })

Notice the @data_val= “false”. It will disable the validation on this field.

Server Side (In Action)

When the model is validated on the post action, ModelState.IsValid will always return false because password is not provided. Here we have to provide the current password to the model and Re-validate the model.

var userObj = db.Users_Info.Where(a => a.Id == users_Info.Id).FirstOrDefault();
if (String.IsNullOrEmpty(users_Info.Password))
{
  users_Info.Password = userObj.Password;
}
ModelState.Clear();
TryValidateModel(users_Info);

Let me explain, first we retrieve current information saved in the database which we are using later to assign to current model if password is not provided. The last two lines actually reset the ModelState to return updated result on ModelState.IsValid.

Comments

1

I ran into trouble with data_val="true". I had a sequence of radio buttons tied to a single property in my model. The data validation only worked when I applied data_val="true" to the first @Html.RadioButtonFor call.

In debugging this, I discovered you can also disable or alter individual rules on the client side by using data_rule_??. The rules can be found in the jquery validation documentation.

for example;

@Html.RadioButtonFor(m => m.Answer, "Yes", new { data_rule_Required = "false" });
@Html.TextBoxFor(m => m.Answer, new { data_rule_minlength = "10" }

Comments

0

If you want to remove validations in MVC5 client-Side you need to do the following:

$("#Email").rules("remove", {
                        "required",
                        "minlength",
                        "email"                           
                        }
                    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.