Online: 14595
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
The output is shown like this to the visitor