HTML and CSS Reference
In-Depth Information
If your views are strongly typed against some model, you can use TextBoxFor() instead of TextBox() ,
as follows:
<%= Html.TextBoxFor(m => m.Age, new {type="number",min="18",max="100"}) %>
In this line of code, the model is assumed to have a property named Age . The Age property is displayed
in a text box that is of type number . The min and max attributes of the text box are set to 18 and 100 ,
Other Validation Attributes
In the preceding sections, you learned about HTML5 input types that let you validate the format of the
data being entered. Beyond the input types, HTML5 adds several other attributes for controlling a few
other aspects of the validation process. This section discusses these techniques.
Dealing with Required Fields
Many data-entry forms expect a value to be entered in one or more text boxes. To enforce this requirement,
ASP.NET developers often use the RequiredFieldValidator control. HTML5 includes an easy alternative to
indicate mandatory data-entry fields. Consider the following markup:
<input id="irstName" type="text" name="irstName" required="required"/>
Notice the required attribute at the end of the <input> element. This is the HTML5 way to indicate
that a given field is mandatory. If you don't supply any value for the firstName text box, the browser shows
an error message and refuses to submit the form even if you haven't written any validation script. Figure
5-11 shows how Chrome throws an error message.
Figure 5-11. Using the required attribute
As you can see, trying to submit the form without entering a value in the text box generates an error
prompting the user to fill out the field.
Pattern-Matching Using Regular Expressions
The new HTML5 input types allow you to validate a few commonly used data formats. However, at times
you need to validate something more complex. A common way to validate such complex formats is regular
expressions. HTML5 also relies on them for performing custom pattern-matching operations. Let's see
h ow.
Search WWH ::

Custom Search