Steven Scott
Steven Scott

Reputation: 11250

Angular Material Reactive Forms use the Validators in the HTML mat-form-field

Looking at the Angular Material demo, I cannot help but notice that the Validators in the TS file (required for instance) also require the required element to be added to the input element in the HTML. I understand that this is from the Angular Material Documentation:

Caution: Use these HTML5 validation attributes in combination with the built-in validators provided by Angular's reactive forms. Using these in combination prevents errors when the expression is changed after the template has been checked.

This is a similar question to this question, except that I want to know if I can extract the validators in the HTML to add the fields automatically, and if so, how?

From the Angular Material Form-Field Overview

<div class="example-container">
  <mat-form-field>
    <input matInput placeholder="Enter your email" [formControl]="email" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>

In the HTML, the input line ends with the word required. What I want to be able to do is somehow extract this by checking the formgroup's email field, and if the email = new FormControl('', [Validators.required, Validators.email]); has the required validator, then add the word required to the <input> HTML tag, so I do not have to change it each time and risk them getting out of sync.

I could then do other things such as the minimum and maximum length, etc.

Upvotes: 0

Views: 2378

Answers (1)

suyash chaudhari
suyash chaudhari

Reputation: 88

If you are using ReactiveForms there is no need to put any validators in HTML. All the validation can be done in the ts file.

Here is an example of a login form with all the validations in ts file.

this.loginForm = this.fb.group({
  mobile: [
    null,
    Validators.compose([
      Validators.required,
      Validators.min(1000000000),
      Validators.pattern("^[0-9]*$")
    ])
  ],
  otp: [null, Validators.compose([
        Validators.required,
        Validators.maxLength(6),
        Validators.minLength(4)])],
});

In HTML

<form [formGroup]="loginForm" (ngSubmit)="login()">

            <mat-form-field >
              <input  matInput type="tel" placeholder="Mobile Number" [formControl]="loginForm.controls['mobile']"
                >
              <mat-error
                *ngIf="loginForm.controls['mobile'].hasError('required') && ( loginForm.controls['mobile'].dirty === true || loginsubmitted === true )">
                Mobile number is <strong>required</strong>
              </mat-error>
              <mat-error
                *ngIf="loginForm.controls['mobile'].hasError('min') && ( loginForm.controls['mobile'].dirty === true || loginsubmitted === true )">
                Mobile number must contain <strong>10 digits</strong>
              </mat-error>
              <mat-error
                *ngIf="loginForm.controls['mobile'].hasError('pattern') && ( loginForm.controls['mobile'].dirty === true || loginsubmitted === true )">
                Invalid Mobile Number
              </mat-error>
            </mat-form-field>



            <mat-form-field >
              <input matInput type="password" placeholder="Enter OTP"
                [formControl]="loginForm.controls['otp']">
              <mat-error
                *ngIf="loginForm.controls['otp'].hasError('required') && ( loginForm.controls['otp'].dirty === true || loginsubmitted === true )">
                OTP is <strong>required</strong>
              </mat-error>
            </mat-form-field>


            <button>LOGIN</button>
          </div>
        </form>

Upvotes: 1

Related Questions