I found the correct answer here. You can disable client-side validation by changing the corresponding HTML attribute in the editor control (e.g., the @Html.EditorFor()
, @Html.TextboxFor()
, etc.). See below for an example:
Using the code-first example above, we will want to create a field for social security numbers. In this field, we want to client-side validation to only use our regular expression, we want the field to be required, and we want the data-type in the database to be nvarchar(9)
. Here is my working code:
Model
<Display(Name:="Social Security Number", ShortName:="SSN", Description:="Employee social security number."),
RegularExpression("^\d\d\d(?:\d\d|-\d\d-)\d\d\d\d$", ErrorMessage:="Please enter a valid social security number."),
StringLength(11, MinimumLength:=9, ErrorMessage:="The social security number must be no more than 9 characters long."),
MaxLength(9)>
Public Property ssn As String
View (razor syntax)
<div class="form-group">
@Html.LabelFor(Function(model) model.ssn, htmlAttributes:=New With {.class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(Function(model) model.ssn, New With {.htmlAttributes = New With {.class = "form-control", .data_val_maxlength_max = "11"}})
@Html.ValidationMessageFor(Function(model) model.ssn, "", New With {.class = "text-danger"})
</div>
</div>
Remarks
- Many of the validations can be turned off completely, you just have
to find the right HTML attribute with a boolean value and set it to
false (e.g.,
data_val="false"
)
- The underscores in my HTML attribute names are converted to hyphens automatically by ASP when the markup is generated.
- The
data_val_maxlength_max
attribute (i.e., the data-val-maxlength-max
attribute) is the name of the HTML attribute that corresponds to the MaxLength(<integer>)
data annotation in the model. In my view code, I change it from 9 to 11 on the client-side (and only on the client-side).