Compare field validation

We will be exploring Compare validation in this section, and since the steps are common for all the built-in validations except the pattern, we will be covering only the validation pattern in the other validation sections. The compare validation will avoid the round-trip between the UI and the service, providing client-side validation for comparing passwords, emails, or even sensitive information such as bank account numbers, which require this compare validation to be in place.

The validation error can be captured in the Compare data annotation in the following scenarios:

  • If the field is NULL or empty or a whitespace

  • If the field has a value which doesn't match the configured field value

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

    public class RegistrationViewModel
{
// Code removed for brevity
[Required(ErrorMessage = "ConfirmPassword is required")]
[Compare("Password")]
public string ConfirmPassword { get; set; }
}

We can verify that if the Password and ConfirmPassword fields don't match then the standard validation error message 'ConfirmPassword' and 'Password' do not match. appears:

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

    public class RegistrationViewModel
{
// Code removed for brevity
[Required(ErrorMessage = "ConfirmPassword is required")]
[Compare("Password", ErrorMessage = "Password does not match")]
public string ConfirmPassword { get; set; }
}

We can also conclude that compare validation consumes the custom validation error message as well. Our test scenario would emit the Password does not match validation error message, shown as follows:

The displayed error message will be cleared once the user starts typing a valid password value in the field.

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

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