Angular provides default validators such as:

Predefined validators

Other predefined validators are also available:

Form validation is triggered by default when the button set to validate a form is pressed.

Custom validators

Additionally, custom validators can be created within the web application and referenced by name. These custom validators can have various configurations such as execution type, name, parameters, and error message.

  1. Execution type - sync/async validator (for more details check this)
  2. Name - name provided by the developer to uniquely identify the validator
  3. Params - if the validator needs inputs to decide if the field is valid or not, you can pass them using this list
  4. Error Message - the message that will be displayed if the field is not valid

The error that the validator returns MUST match the validator name.

custom validator

Custom validator example

Below you can find an example of a custom validator (currentOrLastYear) that restricts data selection to the current or the previous year:

currentOrLastYear
currentOrLastYear: function currentOrLastYear(AC: AbstractControl): { [key: string]: any } {
    if (!AC) {
      return null;
    }

    const yearDate = moment(AC.value, YEAR_FORMAT, true);
    const currentDateYear = moment(new Date()).startOf('year');
    const lastYear = moment(new Date()).subtract(1, 'year').startOf('year');

    if (!yearDate.isSame(currentDateYear) && !yearDate.isSame(lastYear)) {
      return { currentOrLastYear: true };
    }

    return null;
smallerOrEqualsToNumber

Below is another custom validator example that returns AsyncValidatorFn param, which is a function that can be used to validate form input asynchronously. The validator is called smallerOrEqualsToNumber and takes an array of params as an input.

For this custom validator the execution type should be marked as async using the UI Designer.

export function smallerOrEqualsToNumber (params$: Observable<any>[]): AsyncValidatorFn {
  return (AC): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
    return new Observable((observer) => {
      combineLatest(params$).subscribe(([maximumLoanAmount]) => {
        const validationError =
          maximumLoanAmount === undefined || !AC.value || Number(AC.value) <= maximumLoanAmount ? null : {smallerOrEqualsToNumber: true};

        observer.next(validationError);
        observer.complete();
      });
    });
  };
}

If the input value is undefined or the input value is smaller or equal to the maximum loan amount value, the function returns null, indicating that the input is valid. If the input value is greater than the maximum loan amount value, the function returns a ValidationErrors object with a key smallerOrEqualsToNumber and a value of true, indicating that the input is invalid.

For more details about custom validators please check this link.

Using validators in your application can help ensure that the data entered by users is valid, accurate, and consistent, improving the overall quality of your application.

It can also help prevent errors and bugs that may arise due to invalid data, saving time and effort in debugging and fixing issues.