Model:
[Display(Name = "City"] [Required] [RegularExpression(@"^(?!\d$).*$"] [StringLength(20,MinimumLength = 2] public string City { get; set; }
Form:
@Html.LabelFor(x => x.City, new { @class = "control-label" }) @Html.TextBoxFor(x => x.City, new {id="city" })
Script:
<script> $(document).ready(function () { $("#identificationForm").submit(function (e) { var required=document.getElementById("city").required; console.log(required); // e.preventDefault(); }); }); </script>
I want to remove required property if some condition is met.Unable to do this this way.How can i achieve this?
To remove the required attribute, select the element and call the removeAttribute() method on it, passing it required as a parameter, e.g. input. removeAttribute('required') . The removeAttribute method will remove the required attribute from the element.
The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
Just unset the required attribute. If you're trying to unset it after some user action (with javascript) then use the .
JavaScript is case sensitive.
Use
document.getElementById("city").required = false;
Demonstration
Be careful that your code can't work as you try to access the element before it exists. Put your script after the element if you don't execute the code on an event :
<input type="text" id="city" required> <script> if(somecondition is true){ document.getElementById("city").required = false; } </script>
Note also that you can't change this in a submit function and expect your form to be submitted because it's too late : this event handler won't be called if the required field is not filled !
You can use:
document.getElementById("city").removeAttribute("required");
or with jQuery
$('#city').removeAttr('required')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With