Outline

This demo will show you how to create a custom validator. We'll customize how the phoneNumber control can be formatted to be considered valid. Outside our component class, we'll add the validator function:

function phoneValidator(control: AbstractControl): {[key: string]:any } | null {
    const phoneRegex = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
    if (phoneRegex.test(control.value)) { 
        return null; 
    } else {
        return { 
            invalidPhone: true 
        };
    }
}

This returns either null, to show no errors, or an error map with a key/value pair representing the error's name as the key. Generally the "any" value is a boolean to indicate if the error is to be added to the errors list on the control. Instead of explicitly typing out this error map, the ValidationErrors type alias can be used. For the phoneValidator, we'll return an error object with a key of invalidPhone and add it to the phoneNumber control's errors list if it doesn't match the pattern of the phoneRegex.

We'll also learn how to add updateOn: "blur" to the form control. This way, the error message only shows up once the user is done typing in the phoneNumber and has left the field.

 

I finished! On to the next chapter