RegularExpression field validation

Regular expression validation is the only solution used for most validations such as email, phone number, zip code, username, password, and so on. Most of the patterns used with regular expressions are wrapped into separate validations. Still, the usage is vast and requires a method to define custom validation. That's where RegularExpression validation comes in handy.  Lets investigate regular expressions in this section.

If the field value doesn't follow the defined regular expression pattern, then a validation error would be returned by the engine. For instance, if the regular expression is configured to contain only letters of the alphabet, then any other character inclusion would throw a validation error.

The RegularExpression attribute/data annotation can be configured as follows:

    public class Person
{
public int Id { get; set; }
[Required(ErrorMessage = "First Name is required")]
[RegularExpression("^[a-zA-Z]+$")]
public string FirstName { get; set; }
// Code removed for brevity
}

If the field value does not match the regular expression, then the validation error, The field Username must match the regular expression '^[a-zA-Z]+$'.", would be thrown, which is shown as follows:

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

    public class Person
{
public int Id { get; set; }
[Required(ErrorMessage = "First Name is required")]
[RegularExpression("^[a-zA-Z]+$", ErrorMessage = "Only
alphabets were allowed")]

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

The preceding method will force EF to emit a custom error message, Only alphabets were allowedif the field contains invalid data during validation, which is shown as follows:

We have looked, exhaustively, at RegularExpression field validation and other built -in validations in this chapter. We also built validations for the blogging system we are building along the way.

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

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