Tuesday, 23 July 2013

C# Tips : String Length Validation using Annotations in ASP.Net MVC framework

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.

[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 :
 String Length Validation using Annotations in ASP.Net MVC framework
(To view original image , click on image)


Below are the books that you would like :

1 comment: