Error when adding custom validation for angular reactive form

  angular, forms, validation

I’ve created a simple custom validation function.

import { AbstractControl, ValidatorFn } from "@angular/forms";

export function firstLeterUpperCase():ValidatorFn{
    return (control:AbstractControl) =>{
        const value = <string>control.value;
        if(!value) return;
        if(value.length === 0) return;
        const firstLetter = value[0];
        if(firstLetter  !== firstLetter.toUpperCase())
        {
            return{
                  firstLeterUpperCase:{
                   message:"First letter must be uppercase."
               }
            }
        }
        return
    }
}

but I’ve got the following error. Not sure where I’m doing wrong.

Error: src/app/validators/firstLetterValidator.ts:4:5 – error TS2322: Type ‘(control: AbstractControl) => {} | undefined’ is not assignableenter code here to type ‘ValidatorFn’.
Type ‘{} | undefined’ is not assignable to type ‘ValidationErrors | null’.
Type ‘undefined’ is not assignable to type ‘ValidationErrors | null’.

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.