Benutzer:MovGP0/Angular/Forms Validation

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

Forms Validation

[Bearbeiten | Quelltext bearbeiten]
<div *ngIf="name.errors && (name.dirty || name.touched)"
     class="alert alert-danger">
    <div [hidden]="!name.errors.required">
      Name is required
    </div>
    <div [hidden]="!name.errors.minlength">
      Name must be at least 4 characters long.
    </div>
    <div [hidden]="!name.errors.maxlength">
      Name cannot be more than 24 characters long.
    </div>
</div>

Custom Validator

[Bearbeiten | Quelltext bearbeiten]
import { FormControl } from '@angular/forms';

function validateEmail(c: FormControl) {
  let EMAIL_REGEXP = ...

  return EMAIL_REGEXP.test(c.value) ? null : {
    validateEmail: {
      valid: false
    }
  };
}
Apply Validator
import {Component, OnInit} from '@angular/core'

@Component(
  // ...
)
export class Cmp {

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = new FormGroup({
      name: new FormControl('', Validators.required)),
      street: new FormControl('', Validators.minLength(3)),
      city: new FormControl('', Validators.maxLength(10)),
      zip: new FormControl('', Validators.pattern('[A-Za-z]{5}')),
      email: new FormControl('', validateEmail)
    });
  }
}

Validator Directive

[Bearbeiten | Quelltext bearbeiten]
import { Directive } from '@angular/core';
import { NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[validateEmail][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useValue: validateEmail, multi: true }
  ]
})
class EmailValidator {}
Usage
import { EmailValidator } from './email.validator';

@NgModule({
  ...
  declarations: [AppComponent, EmailValidator],
})
export class AppModule {}
<form novalidate>
  ...
  <input type="email" name="email" ngModel validateEmail>
</form>

|}