RegEx应用程序采用角度2形式

时间:2016-12-10 16:23:56

标签: javascript html regex angular

我正在尝试生成错误,以防有人在输入框中输入错误的模式,但这似乎不起作用。我想要做的是下面:

<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" (ngSubmit)="f.form.valid && register()" #f="ngForm" novalidate>
    <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !Username.valid }">
        <label for="Username">Username</label>
        <input type="text" class="form-control" name="Username" [(ngModel)]="model.Username" #Username="ngModel" required />
        <div *ngIf="f.submitted && !Username.valid" class="help-block">Username is required</div>
    </div>

    <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !Email.valid }">
        <label for="Email">Email</label>
        <input type="email" class="form-control" name="Email" [(ngModel)]="model.Email" 
               #Email="ngModel" required pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"/>
        <div *ngIf="f.submitted && !Email.valid" class="help-block">Email is required</div>
        <div *ngIf="!pattern" class="alert alert-danger">Wrong Pattern</div>
    </div>
</form>

有关错误信息(错误模式)的div只是粘在页面上,无论我输入正确还是错误的电子邮件都没有任何反应。请帮帮我!

1 个答案:

答案 0 :(得分:2)

您可以使用被动表单和自己的自定义验证程序。我们假设您的表单中只有email字段;

//html
<form [formGroup]="yourFormName" (ngSubmit)="yourSubmitMethod()">
     <div [class.has-danger]="_yourFormControlNameForEmailField.touched && _yourFormControlNameForEmailField.invalid" [class.has-success]="_yourFormControlNameForEmailField.dirty && _yourFormControlNameForEmailField.valid">
          <label for="email">Email</label>
          <input type="email" name="email" formControlName="yourFormControlNameForEmailField" [class.form-control-danger]="_yourFormControlNameForEmailField.touched && _yourFormControlNameForEmailField.invalid" [class.form-control-success]="_yourFormControlNameForEmailField.dirty && _yourFormControlNameForEmailField.valid">
     </div>
</form>

//in ts
export class YourClassName {
     yourFormName: FormGroup;
     _yourFormControlNameForEmailField = new FormControl(model.Email, [<any>EmailValidator.emailPattern]);
     constructor(private formBuilder: FormBuilder, ...){
           ...
     }

     ngOnInit(){
          //create a form group with form control(s)
          this.yourFormName= this.formBuilder.group({
               yourFormControlNameForEmailField: this._yourFormControlNameForEmailField
          });
     }

     yourSubmitMethod(){
          ...
     }
}

//EmailValidator
import { AbstractControl } from '@angular/forms';

export class EmailValidator {
    static emailPattern(c: AbstractControl): { [key: string]: any } {
        let regexp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        //if test is unsuccessful, return key(emailPattern)-value(false) pair
        return regexp.test(c.value) ? null : { emailPattern: false };
    }
}