Client-Side Validation using jQuery

Leave a Comment
With client-side validation, the inputs are checked as soon as they are submitted, so there is no postback to the server, there’s no page refresh, and the results are shown instantly to the user!

To begin with client-side validation, go ahead and reference the jQuery validation plugin scripts in the view:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>

Example
<form action="/Auctions/Create" method="post" novalidate="novalidate">
<div class="validation-summary-errors" data-valmsg-summary="true">
<ul><li>The Description field is required.</li>
<li>The Title field is required.</li>
<li>Auction may not start in the past</li>
</ul></div><p><label for="Title">Title</label>
<input class="input-validation-error"
data-val="true"
data-val-length="Title cannot be longer than 50 characters"
data-val-length-max="50"
data-val-required="The Title field is required."
id="Title" name="Title" type="text" value="">
<span class="field-validation-error"
data-valmsg-for="Title"
data-valmsg-replace="false">*</span>
</p><p><label for="Description">Description</label>
<input class="input-validation-error"
data-val="true"
data-val-required="The Description field is required."
id="Description" name="Description" type="text" value="">
<span class="field-validation-error"
data-valmsg-for="Description"
data-valmsg-replace="false">*</span>
</p><p><label for="StartPrice">StartPrice</label>
<input data-val="true"
data-val-number="The field StartPrice must be a number."
data-val-range="The auction's starting price must be at least 1"
data-val-range-max="10000"
data-val-range-min="1"
data-val-required="The StartPrice field is required."
id="StartPrice" name="StartPrice" type="text" value="0">
<span class="field-validation-valid"
data-valmsg-for="StartPrice"
data-valmsg-replace="true"></span>
</p><p><label for="EndTime">EndTime</label>
<input data-val="true"
data-val-date="The field EndTime must be a date."
id="EndTime" name="EndTime" type="text" value="">
<span class="field-validation-valid"
data-valmsg-for="EndTime"
data-valmsg-replace="true"></span>
</p><p><input type="submit" value="Create">
</p></form>

With unobtrusive JavaScript and client-side validation enabled, ASP.NET MVC renders the validation criteria and corresponding messages as data-val- attributes.

The jQuery validation plug-in will use these attributes to figure out the validation rules and the corresponding error messages that will be displayed if the rules are not satisfied.

0 comments:

Post a Comment