Rezwanul Haque
Rezwanul Haque

Reputation: 13

Error when adding custom validation for angular reactive form

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'.

Upvotes: 1

Views: 3821

Answers (2)

Nedu
Nedu

Reputation: 21

I guess you are using the newest version of Angular. You can try this code:

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


 export function firstLetterUppercase(): ValidatorFn {
        return (control: AbstractControl) : ValidationErrors | null => {
            const value  = <string>control.value;
            if(!value) return null;
            if(value.length === 0) return null;
    
            const firstLetter = value[0];
            if(firstLetter !== firstLetter.toUpperCase()){
                return {
                    firstLetterUppercase : {
                        message: 'The first letter must be uppercase'
                    }
                }
            }
            return null;
        }
    }

Upvotes: 2

Francesco Lisandro
Francesco Lisandro

Reputation: 720

Try with a simple function that does what you need:

export function firstLetterUppercase(): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    return /^[A-Z]/.test(control.value) ? null : { firstLetterUpperCase: true };
  };
}

Where we use the regex /^[A-Z]/ to test the control.value and see if it has the first letter uppercase. The function will return null if there are no errors otherwise it returns { firstLetterUpperCase: true }. Then associate the validator to your input (read it) and show or hide the error message directly in the template.

<div class="error-message" *ngIf="yourInputName.errors.firstLetterUpperCase">
 First letter must be uppercase.
</div>

Upvotes: 1

Related Questions