Unobtrusive Validation support for Input controls helps you to validate any C1 input control using client side validation. Unobtrusive validation can implement simple client-side validation without writing a bulk of validation code, and improves the user experience simply by adding the right attributes and including the script files.
In a common validation scenario, when we use a validation to validate any control and use client side validation, JavaScript code is generated and rendered as HTML on the web browser. However, with unobtrusive validation inline JavaScript is not generated for rendering to handle client side validation. Instead, it uses HTML5 data-* attributes for client side validations.
Unobtrusive Validation support is available in the following Input controls;
Before implementing the below steps, you need to create a new MVC application using ComponentOne template or Visual Studio template.
Complete the following steps to add the js file references to your application.
Razor |
Copy Code
|
---|---|
<script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/jquery.validate.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> |
Model - Form.cs
Razor |
Copy Code
|
---|---|
using System.ComponentModel.DataAnnotations; namespace UnobtrusiveValidationSample.Models { public class Form { [Required] public string Id { get; set; } [Required] [DataType(DataType.Text)] [MinLength(8)] [MaxLength(30)] public string Name { get; set; } [Required] [DataType(DataType.PhoneNumber)] [Phone] [Range(0, 10000000000)] [StringLength(11)] [MinLength(7)] [MaxLength(10)] public string PhoneNo { get; set; } [Required] [DataType(DataType.EmailAddress)] [EmailAddress] [MinLength(10)] [MaxLength(50)] public string EmailAddress { get; set; } } } |
View - Index.cshtml
Razor |
Copy Code
|
---|---|
@using UnObtrusiveValidationSample.Models; @model Form @using (Html.BeginForm()) { <br /> @Html.LabelFor(m => m.Id) <br /> @Html.EditorFor(m => m.Id) @Html.ValidationMessageFor(m => m.Id) <br /> @Html.LabelFor(m => m.Name) <br /> @Html.EditorFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name) <br /> @Html.LabelFor(m => m.PhoneNo) <br /> @Html.EditorFor(m => m.PhoneNo) @Html.ValidationMessageFor(m => m.PhoneNo) <br /> @Html.LabelFor(m => m.EmailAddress) <br /> @Html.C1().InputMaskFor(m => m.EmailAddress) @Html.ValidationMessageFor(m => m.EmailAddress) <br /> <input type="submit" /> <input type="reset" /> } |