使用模式进行Angular2表单验证

时间:2017-08-21 05:35:34

标签: regex angular angular4-forms

我试图在Angular 4.3.0中使用电子邮件的模式属性,但即使电子邮件正确, field.errors.pattern 也会返回true。 我正在处理现有的代码,而且这种模式已经用于此了。我也无法理解RegEx。

以下是HTML表单

<form #loginform="ngForm" class="form-horizontal  b bg-white padding_default r-2x box-shadow" novalidate role="form">

    <div class="text-danger wrapper text-center" *ngIf="authError">

    </div>
    <div class="animated fadeIn">
        <div class=" m-b-md no-border ">
            <input id="username" type="email" class="form-control input-lg b  text-md" name="username" placeholder="Email" [(ngModel)]="loginData.email"
                autofocus required #username="ngModel" pattern="emailPattern">
            <div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">
                <div *ngIf="username.errors.required">
                    Name is required.
                </div>
                <div *ngIf="username.errors.pattern">
                    Name is invalid
                </div>

            </div>
            <!--<div class="sxo_validate_msg text-danger text-sm" *ngIf="username.touched && isValidEmail">
                            <span>Invalid email address.</span>
                        </div>-->
        </div>

        <div class=" m-b-md no-border">
            <input id="password" type="password" class="form-control input-lg b b-light text-md" name="password" [(ngModel)]="loginData.password"
                placeholder="Password" required #password="ngModel">
            <div class="text-danger sxo_validate_msg text-sm" *ngIf="password.dirty && password.invalid">
                <span *ngIf="password.required">Password is required.</span>
            </div>
        </div>

        <div class="m-b-md m-t-md">
            <label class="i-checks text-sm">
                <input name="rememberme" id="login-remember" type="checkbox" [(ngModel)]="loginData.rememberMe"><i></i> <a href="#">Remember me</a>
            </label>
        </div>

        <div class="controls m-t-md">

            <div class="m-b-lg" *ngIf="showCaptche">
                <re-captcha [site_key]="model.key" (captchaResponse)="setResponse($event)"></re-captcha>

                <!--<div vc-recaptcha
                                theme="'light'"
                                key="model.key"
                                on-create="setWidgetId(widgetId)"
                                on-success="setResponse(response)"
                                on-expire="cbExpiration()"></div>-->
            </div>
            <input class="btn btn-lg btn-dark btn-block" value="Login" (click)="login()" [disabled]="!loginform.form.valid" />
            <div [hidden]="!message" class="alert alert-danger sxo_validate_msg p-t-xs p-b-xs">
                {{message}}
            </div>
        </div>
    </div>


</form>

以下是模式

emailPattern:any =  new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

3 个答案:

答案 0 :(得分:2)

我也遇到了同样的问题而且我不知道为什么正则表达式似乎不适用于我的Angular 4项目。我开始在Angular的 FormGroup 中使用 Validators ,电子邮件验证在我的项目中就像魅力一样。

这是我编辑个人资料页面的代码片段( edit-profile.component.html ):

<form [formGroup]="editProfileForm" class="form-horizontal" (ngSubmit)="EditProfile()" >
    <div class="form-group">
       <label for="email" class="col-md-4 control-label">E-Mail Address </label>
       <div class="col-md-6">
          <input id="email" type="email" class="form-control" formControlName="email" [(ngModel)]="user.email" required autofocus >
       </div>
    </div>
    <span class="help-block">
       <strong>{{ errors.email }}</strong>
    </span>
    <div class="form-group">
       <div class="col-md-6 col-md-offset-4">
          <button type="submit" class="btn btn-primary" [disabled]="editProfileForm.pristine">
            Update
          </button>
       </div>
    </div>
</form>

并在 edit-profile.component.ts 文件中:

import { NgForm, FormGroup, FormBuilder, FormArray, FormControl, Validators } from '@angular/forms';

  private errors = {
      email: '',
  };

  public editProfileForm: FormGroup;

  constructor(
    private fb: FormBuilder,
  ) {
    this.createForm();
  }

  createForm() {
    // constructor + form Validator
    this.editProfileForm = this.fb.group({
      email: ['', Validators.compose([Validators.required, Validators.email])],
    });
   }

   EditProfile() {
    if (this.editProfileForm.invalid) {
      if (this.editProfileForm.controls['email'].hasError('required')) {
        this.errors.email = 'E-mail name cannot be empty';
      } else if (this.editProfileForm.controls['email'].hasError('email')) {
        this.errors.email = 'E-mail is not valid';
      } 
    } else {
    // submit the form
    }
  }

希望这有帮助!

答案 1 :(得分:0)

Angular 4有一个内置的email验证标记,可以在输入中添加。 E.g:

<input type="email" id="contactemail" email>
  

这对于一系列数字和字母有效,然后是@ then   另一系列的信件。在@之后它不会占到点数    - 为此你可以在输入和标准正则表达式中使用“pattern”标签。

或者如果你想使用模式试试这个

<input type="text" name="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required email/>

答案 2 :(得分:0)

了解/学习RegExp:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

以下内容应该有效:

 emailPattern:any =  new 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,}))$/);