html5 - How to display message on pattern validation? -
i added pattern attribute 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 add message display if input not correct?
something wont work:
<div [hidden]="!name.errors.pattern" class="alert alert-danger"> name must match pattern </div>
i advise use reactiveforms
instead of templatedrivenforms
manage validation patterns , 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 login form validation. note how md-hint
elements show when form has validation errors on specific fields.
you can set interface match reactiveform
. here interface linked example :
export interface account { account: { email: string; password: string; } }
the typescript example snippet :
import { formgroup, formbuilder, validators } '@angular/forms'; import { emailregex } 'app/shared/shared.interface'; // imported regex validator ... user: formgroup; ngoninit() { ... // init reactive form this.user = this.formbuilder.group({ account: this.formbuilder.group({ email: ['', [validators.required, validators.pattern(emailregex)]], password: ['', validators.required] }) }); }
please note how form groups match interface. also, can set form values there if want to, can see fields email
, password
set empty string value. note can add validators want in array linked field.
you can access form values on submit()
directly primary formgroup
:
this.user.value.account.email
if example wasn't enough, suggest read todd motto's guide on reactiveforms
explained :
Comments
Post a Comment