centralised validation angular forms

Published

I am implementing validation in my angular reactive form and want to centralise the validation. The service is injected in the component. Do let me know if my approach is correct. Is it fine passing the form instance and field name to the service ?

Component markup

 <div>
  <label>Phone number</label>
       <input type="text" placeholder="Phone number" formControlName="phoneNo"
    [ngClass]="{'isError' : helper.validateField(form,'phoneNo')}" />
</div>

Service

@Injectable({ providedIn: 'root' })
export class HelperService {
    //private form: FormGroup;
    public submitted: boolean;

    validateField(form: FormGroup,field: string) {
        return (this.submitted || form.get(field).touched) && form.get(field).errors?.required;
      }
}

Source: Angular Questions

Published
Categorized as angular, angular-reactive-forms Tagged ,

Answers

Leave a Reply

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

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq