This tutorial shows you how to use MinLengthAttribute in C#.NET.
The MinLengthAttribute allows you to specify the minimum length of string data allowed in a property.
For example
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
If you want to limit the FirstName property you can modify your code as the following
[Required]
[MinLength(10)]
public string FirstName { get; set; }
Remember add using to System.ComponentModel.DataAnnotations
If you enter a string containing less than 10 characters, you will get the following error message: The field FirstName must be a string or array type with a minimum length of '10'.
If you want to custom an error message for MinLengthAttribute you can modify your code as shown below.
[Required]
[MinLength(10, ErrorMessage = "The first name field must be at least 10 characters long")]
public string FirstName { get; set; }
You can do the same for MaxLengthAttribute