Search code examples
c#asp.net-mvcunobtrusive-validation

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,


Solution

  • 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; }