ASP.NET MVC > Models

Validating string length in Model property in ASP.NET MVC

How to validate a model field value for a particular string length?


To validate for a string length in Model property, we use StringLength attribute.

/Models/PersonalDetail.cs

using System; 
using System.Collections.
Generic; using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;  
namespace WebApplication1.Models
 {  
   public class PersonalDetail   
  {
         [Key]       
     [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt ion.Identity)]     
         public int AutoId { get; set; }  
[StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please write your LastName")] public string LastName { get; set; } public int Age { get; set; } [Display(Name = "Is Active?")]
public bool Active { get; set; } } }

Notice the FirstName property that has been decorated with StringLength attribute that accepts few parameter. In this case, the parameters are

  1. First parameter - the maximum string length accepted
  2. Second parameter - the minimum string lenght required
  3. Third parameter - the error message to show to the user in case any of above two parameters are not valid.

The output is shown like this to the visitor

 Views: 3946 | Post Order: 36



Write for us