0

I need to write the custom validator for the Angular template-driven form where one any non-empty input would be sufficient to make the form valid.

Consider the following Angular form with the two input fields and the submit button:

<form name="myform" (ngSubmit)="userForm.form.valid && saveData()" #userForm="ngForm" novalidate>

    <input type="text"
        [(ngModel)]="phoneNumber"
        name="phoneNumber"
        #phoneNumber="ngModel"
        pattern="\+[1-8]{1-3}\([0-9]{3}\)[0-9]{7}" />

    <input type="text"
        [(ngModel)]="privateEMail"
        name="privateEMail"
        #privateEMail="ngModel"
        pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$" />

    <button type="submit" [disabled]="!userForm.form.valid">Submit</button>

</form>

The requirement - to make the form valid (additionally to the inputs pattern validation) if one any of both inputs should be not empty. To write the custom validator for the input controls has no sense - it would be limited with the scope of its own values only. To subscribe to the form event statusChanges brings also noting - this info is read only. When to write the control custom validator (like for the input control) and apply it to the form then it would not work - it seems to would not be called by the form.

What is the proper way to write the custom validator for the Angular template-driven form?

2
  • 1
    from my experience where I have to validate forms based on regex patterns or any other custom validation I never use template driven forms, as reactive forms are much more powerful and in my opinion readable cause the template doesnt get as much polluted as with template driven forms. Commented Apr 30, 2020 at 21:54
  • But if the requirement is to present the form as valid if there wasnt entered any data you have to ask wether it was touched or dirty like so: (userForm.controls. privateEMail?.dirty || userForm.controls. privateEMail?.touched) Commented Apr 30, 2020 at 22:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.