简体   繁体   中英

How to remove 'required' setting from form field using jQuery unobtrusive validation

I am having some trouble removing 'required' field validation from a field on a form that is using jQuery validation and jQuery unobtrusive.

I have the following razor view -

    <div class="form-group @Html.Raw(Html.HasError(x => x.TargetNumber) ? "has-error" : null)">
        <div class="col-md-12">
            <p><strong>How much will you raise</strong></p>
        </div>
        <div class="col-sm-6">
            @Html.TextBoxFor(x => x.TargetNumber, new { id = "TargetNumber", @class = "form-control", placeholder = "Target", type = "number", Value="Target" })
            @Html.ValidationMessageFor(x => x.TargetNumber, null, new { @class = "error" })
        </div>
    </div>

and view model

    [Required(ErrorMessage = "Please enter a valid value.")]
    [Range(100, Double.PositiveInfinity, ErrorMessage = "The minimum amount for this event is £100")]
    public double TargetNumber { get; set; }

I have tried the following to make the field non required -

  • Removed the [Required] attribute but still the field gets the form markup is renderered with various data attributes and is required
  • Added data_val="false" (and required="false") to 'TextBoxFor' in the view

Yet, still the field is flagged as required on submit.

Can anyone please suggest a way that I can make this field non required.

Thanks,

For structs, the RequiredAttribute only changes the error message, the properties are always required.
If you don't want them to be required, you need to make them nullable:

[Range(100, Double.PositiveInfinity, ErrorMessage = "The minimum amount for this event is £100")]
public double? TargetNumber { get; set; }

You have to set up a rule for your property using jQuery like so:

     $('#myForm').validate({

        rules: {

               TargetNumber: {

                              required: function (element) {
                                         return false;
                                      }

                           }
             }


    });

TargetNumber should be the name attribute and not the id attribute. I think for MVC it automatically assigns the name attribute based on the model name, but check in your developer tools to see what value is being assigned to the name attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM