Click Here to Download MVC_String_Length_ValidationUsingAnnotations.zip Example.
We can do string length validation using Annotations in MVC. We are using "StringLength" attribute for validation in this attribute we can specify how many characters we want to allow for particular field. In this, we can specify Maximum Length and Minimum Length. Minimum Length is an optional.
We can use more than one attribute on field.
Here is example for this.
We take "customer" example. In this, we apply string length for "FirstName" field. Maximum Length 20 and Minimum Length 2. When user violate this rule at that time validation message occurred. Also, we apply only Maximum Length 10 for "LastName" field.
At the view side we have to add this code :
This is used to display error messages at client side.
Here is Code for this.
Model (Customer.cs):
Output :
Below are the books that you would like :
We can do string length validation using Annotations in MVC. We are using "StringLength" attribute for validation in this attribute we can specify how many characters we want to allow for particular field. In this, we can specify Maximum Length and Minimum Length. Minimum Length is an optional.
We can use more than one attribute on field.
Here is example for this.
We take "customer" example. In this, we apply string length for "FirstName" field. Maximum Length 20 and Minimum Length 2. When user violate this rule at that time validation message occurred. Also, we apply only Maximum Length 10 for "LastName" field.
[Required] [StringLength(20,MinimumLength=2)] public string FirstName { get; set; } [StringLength(10)] public string LastName { get; set; }
At the view side we have to add this code :
@Html.ValidationMessageFor(model => model.FirstName,"", new { style="color:red"}) @Html.ValidationMessageFor(model => model.LastName,"", new { style="color:red"})
This is used to display error messages at client side.
Here is Code for this.
Model (Customer.cs):
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MVCValidationUsingAnnotations.Models { public class Customer { public int CustomerID { get; set; } [Required] [StringLength(20,MinimumLength=2)] public string FirstName { get; set; } [StringLength(10)] public string LastName { get; set; } public string Email { get; set; } } }
Output :
(To view original image , click on image) |
Below are the books that you would like :
This blog gives very important info about .Net Thanks for sharing
ReplyDelete.Net Online Training Hyderabad