Part 11 Angular Tutorial | Form validations | Custom Form Validations | Services in Angular

preview_player
Показать описание
Custom validations and Services in Angular

Custom validators allow you to implement your own validation logic and extend the built-in validators provided by Angular.

Here's an example of how to create a custom validator in Angular:

export function forbiddenNameValidator(forbiddenName: RegExp): ValidatorFn {
...
}

In this example, we define a forbiddenNameValidator function that takes a regular expression as an argument and returns a ValidatorFn. The ValidatorFn takes an AbstractControl as an argument and returns a ValidationErrors object if the control fails validation, or null if it passes validation.

The validator checks if the control's value matches the regular expression provided as an argument. If the value matches the regular expression, the validator returns a ValidationErrors object with a forbiddenName key and the value of the control, indicating that the control failed validation. If the value does not match the regular expression, the validator returns null, indicating that the control passed validation.

In this example, we import the forbiddenNameValidator and use it to add a custom validator to the name control. We pass a regular expression that matches the string 'admin' as an argument to the validator.

In the template, we use the *ngIf directive to show an error message if the name control fails validation. We check if the control has an error with the key forbiddenName and display a message indicating that the value is not allowed.
Рекомендации по теме
join shbcf.ru