Jonathan
Jonathan

Reputation: 342

.net mvc 5 unobtrusive disable field validation

this is a short answer. does anyone know how to disable a field validation on javascript using .net mvc unobtrusive validation?. I have a view model field with [Require] Datannotation but depending user's decision could be a required or not in the view, i would manage view model validation on my controller using modelState.remove("field").

i appreciate your help

Upvotes: 2

Views: 2780

Answers (2)

ediblecode
ediblecode

Reputation: 11971

You want to amend the rules based on the user's decision. When the field is no longer required, do the following:

$('#Property').rules('remove', 'required')

You can wrap this in a listener on the #OtherProperty:

$('#OtherProperty').change(function(e) {

  if (someCondition) {
    $('#Property').rules('remove', 'required')
  } else {
    $('#Property').rules('add', 'required')
  }

});

Upvotes: 2

heymega
heymega

Reputation: 9391

I believe the dataannotation just adds the HTML required attribute. This gets added when you use the HTML helpers such as @Html.TextboxFor. I believe it checks this attribute with the unobtrusive validation library.

Using javascript or jquery you should be able to dynamically remove or add this attribute.

Example - Removing required attribute in jQuery

$('#MyInput').removeAttr('required');

Update

It doesn't add the required attribute it adds data-rule-required="true"

Just remove this attribute. It it still doesn't update you might need to reinitialise the validation code.

Hope this helps!

Upvotes: 0

Related Questions