The MaxLength validation is helpful for creating constraints on certain fields such as Username, Zip code, and so on. We will investigate MaxLength validation in this section.
The validation error can be captured in the MaxLength data annotation if the field value length is greater than the configured length. For instance, if the maximum length is configured as 30, then if the length of total characters provided in the field is greater than 30, the max length validation error would be thrown.
The MaxLength attribute/data annotation can be configured as follows:
public class RegistrationViewModel
{
[Required(ErrorMessage = "Username is required")]
[MinLength(6, ErrorMessage = "Username needs minimum 6
characters")]
[MaxLength(30)]
public string Username { get; set; }
...