playerone
playerone

Reputation: 1127

How to display message on pattern validation?

I added pattern attribute to template

<input class="form-control" type="text" id="elementName"
                                   [(ngModel)]="elementName" name="elementName"
                                   (input)="onElementNameChanged()" #name="ngModel" required pattern="[A-Za-z0-9_)*\S]*" >

How to add message to display if input is not correct?

Something like wont work:

<div [hidden]="!name.errors.pattern"
     class="alert alert-danger">
     Name must match pattern
</div>

Upvotes: 0

Views: 15894

Answers (1)

Alex Beugnet
Alex Beugnet

Reputation: 4071

I strongly advise you to use ReactiveForms instead of TemplateDrivenForms as they are really good to manage validation patterns and messages.

An HTML snippet example :

<form novalidate [formGroup]="user" (ngSubmit)="onSubmit()">

    <div formGroupName="account">

      <md-input-container>
        <input md-input type="text" placeholder="{{'USER.EMAIL' | translate}} *" formControlName="email" autocomplete="off">
        <md-hint class="error" *ngIf="user.get('account.email').hasError('required') && user.get('account.email').touched">
          {{'VALIDATOR.EMAIL_RQ' | translate}}
        </md-hint>
        <md-hint class="error" *ngIf="user.get('account.email').hasError('pattern') && user.get('account.email').touched">
          {{'VALIDATOR.WRONG_EMAIL' | translate}}
        </md-hint>
      </md-input-container>

      <md-input-container>
        <input md-input type="password" placeholder="{{'USER.PASSWORD' | translate}} *" minlength="6" formControlName="password" autocomplete="off">
        <md-hint class="error" *ngIf="user.get('account.password').hasError('required') && user.get('account.password').touched">
          {{'VALIDATOR.PWD_RQ' | translate}}
        </md-hint>
      </md-input-container>

    </div>

    <button md-raised-button [disabled]="!user.valid || submitted" color="accent" type="submit" class="submit-button">
      {{'LOGIN.BUTTON' | translate}}
    </button>

  </form>

This HTML example shows a login form with validation. Note how the md-hint elements show only when the form has the validation errors on the specific fields.

You can actually set an interface to match your ReactiveForm. Here is the interface linked to the example :

export interface Account {
  account: {
    email: string;
    password: string;
  }
}

The TypeScript example snippet :

  import { FormGroup, FormBuilder, Validators } from '@angular/forms';
  import { EmailRegex } from 'app/shared/shared.interface'; // Imported regex for validator


  ...

  user: FormGroup;

  ngOnInit() {
    ...

    // Init your reactive form
    this.user = this.formBuilder.group({
      account: this.formBuilder.group({
        email: ['', [Validators.required, Validators.pattern(EmailRegex)]],
        password: ['', Validators.required]
      })
    });
  }

Please note how the form groups match the interface. Also, you can set the form values there if you want to, but as you can see my fields email and password are set with an empty string value. Note that you can also add as much validators as you want in the array linked to the field.

You can then access your form values on submit() directly from your primary FormGroup :

this.user.value.account.email

If this example wasn't good enough, I strongly suggest you read Todd Motto's guide on ReactiveForms which is really well explained :

https://toddmotto.com/angular-2-forms-reactive

Upvotes: 8

Related Questions