08 November 2018

Validation formGroup multiple patterns trong Angular 2

Validation FormGroup Multi Patterns
Tạo project Angular bấm vào đây
app.component.html
<input formControlName="name" class="form-control" type="text" [ngClass]="{
        'is-valid': (f?.name.valid && (f?.name.touched || isSubmit)),
        'is-invalid': (f?.name.invalid && (f?.name.touched || isSubmit))}">
app.component.ts
private validate() {
    this.formGroup = new FormGroup({
      name: new FormControl(
        "",
        Validators.compose([
          this.validName,
          Validators.maxLength(25),
          Validators.minLength(5),
          Validators.pattern("^[0-6]+$"),
          Validators.required,
          this.regexValidator(new RegExp("^[1-4]+$"), { pattern2: "false" }),
          this.regexValidator(new RegExp("^[1-3]+$"), { pattern3: "false" })
        ])
      ),
      address: new FormControl("", Validators.required),
      email: new FormControl("", [Validators.required, Validators.email]),
      phone: new FormControl("", Validators.required),
      sex: new FormControl("", Validators.required)
    });
  }
 
  get f() {
    return this.formGroup.controls;
  }
 
  //Check duplicate user
  private validName(fc: FormControl) {
    if (
      fc.value.toLowerCase() === "abc123" ||
      fc.value.toLowerCase() === "123abc"
    ) {
      return { validName: true };
    } else {
      return null;
    }
  }
 
  //Group Pattern Validator
  private regexValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      if (!control.value) {
        return null;
      }
      const valid = regex.test(control.value);
      return valid ? null : error;
    };
  }
app/app.module.ts
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
  imports: [
    FormsModule, // Để sử dụng [(ngModel)]
    ReactiveFormsModule  // Để sử dụng formControlName
  ],
})
styles.css
@import url('https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css');

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang