29

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?

Fals
  • 6,813
  • 4
  • 23
  • 43
user2137186
  • 817
  • 6
  • 22
  • 39
  • With Jquery: $("#city").removeAttr("required"); or use document.getElementById("city").removeAttribute('required'); – kevhann80 Aug 07 '13 at 19:18
  • Are you using JqueyVal? If yes, removing the required isn't the only thing! – Fals Aug 07 '13 at 20:32
  • possible duplicate of [How to set HTML5 required attribute in Javascript?](http://stackoverflow.com/questions/18770369/how-to-set-html5-required-attribute-in-javascript) –  Apr 24 '14 at 23:03

9 Answers9

58

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 !

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
15

You can use:

document.getElementById("city").removeAttribute("required");

or with jQuery

$('#city').removeAttr('required')
j08691
  • 204,283
  • 31
  • 260
  • 272
5

You shoud do this:

if(somecondition is true)
{
  var city = document.getElementById("city");
  city.removeAttribute('required');
}
Fals
  • 6,813
  • 4
  • 23
  • 43
1

By the time the On Submit function is to remove the required attribute, the form would have already passed validation. The steps are first you have to disable validation then you will be able to submit the form with the required fields empty. Next remove the required attributes and finally manually invoke validation via $.validator.unubtrusive.parse(form) and this will now validate the form by invoking the other validation types such as string length and formatting, everything else except the required attributes. Check if form.valid() then submit() else do nothing.

Stanislav
  • 2,629
  • 1
  • 29
  • 38
rasmicah
  • 11
  • 4
1

In php its very easy, this will not validate your form while submitting,

<input type="submit" onclick="return confirm('Are you sure?')" value="Abort Test" formnovalidate>
Sarfaraz Ansari
  • 119
  • 1
  • 8
0

Not sure if anyone has figured out a better way to do this yet and it might not be the most efficient way to do it but you could use PHP to get this done. If the condition you are looking to meet is known before the page loads then you can have this:

<input type="text" id="city" 

<?php
     if (condition_is_met) {
          echo ">";
     } else {
          echo "required>";
     }
?>
0

If you put your text fields in a form, it is possible to overwrite the required field with a special attribute called novalidate. This is the syntax: <form novalidate> .. </form>

Here is an example:

<form novalidate>
  Zip code: <input type="text" name="zipcode" pattern="[0-9]{5}" required><br/>

  <input type="submit">
</form>

The novalidate Attribute Here is a link with two live demos using novalidate attribute.

S. Mayol
  • 2,565
  • 2
  • 27
  • 34
0

Or in the moment that form is submitted you can disabled it if it's null:

if($("#City").val().trim().length == 0) $("#City").attr("disabled", true);

0

This works for me with data annotations. Use the "rules" function.

$("#FileUpload").rules("remove", "required");

and to add:

$("#FileUpload").rules("add", "required");

UPDATE: This will fix frontend validation but backend validation still fails. To make the ModelState valid, I change the ValidationState of that input.

ModelState["FileUpload"].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;

I do check to make sure that's the only error too:

if (ModelState["FileUpload"].Errors.Count == 1)
    if (ModelState["FileUpload"].Errors[0].ErrorMessage.Equals("The FileUpload field is required."))
        ModelState["FileUpload"].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;
tdahman1325
  • 210
  • 3
  • 6