MaxLength field validation

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; }
// Code removed for brevity
}

If the field value does not meet the maximum length requirement, then the validation error, The field Username must be a string or array type with a maximum length of '30'. would be thrown, whereas the field name and length of the error message is based on the field name and configuration, as follows:

We can configure the custom error message for each model field, shown as follows:

    public class RegistrationViewModel
{
[Required(ErrorMessage = "Username is required")]
[MinLength(6, ErrorMessage = "Username needs minimum
6 characters"
)]
[MaxLength(6, ErrorMessage = "Username cannot exceed
30 characters")]

public string Username { get; set; }
// Code removed for brevity
}

The preceding method will force EF to emit a custom error message, Username cannot exceed 30 characters, if the field contains invalid data during validation, shown as follows:

We have looked, exhaustively, at MaxLength field validation; let's explore RegularExpression validation in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset