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.
This topic comprises of four steps:
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
|
---|---|
@model Form @section Scripts{ @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } <form> <br /> <label asp-for="Id"></label> <br /> <input asp-for="Id" /> <span asp-validation-for="Id"></span> <br /> <label asp-for="Name"></label> <br /> <input asp-for="Name" /> <span asp-validation-for="Name"></span> <br /> <label asp-for="PhoneNo"></label> <br /> <input asp-for="PhoneNo" /> <span asp-validation-for="PhoneNo"></span> <br /> <label asp-for="EmailAddress"></label> <br /> <c1-input-mask for="EmailAddress"></c1-input-mask> <span asp-validation-for="EmailAddress"></span> <br /> <input type="submit" /> <input type="reset" /> </form> |