1

我正在尝试在 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);
4

3 回答 3

2

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

这是我的编辑个人资料页面 ( 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
    }
  }

希望这可以帮助!

于 2017-08-21T08:58:56.767 回答
0

Angular 4 有一个内置的email验证标签,可以添加到输入中。例如:

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

这将适用于一系列数字和字母,然后是 @,然后是另一系列字母。它不会考虑 @ 之后的点 - 因为您可以在输入和标准正则表达式中使用“模式”标签。

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

<input type="text" name="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required email/>
于 2017-08-21T05:43:59.570 回答
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,}))$/);
于 2017-08-21T07:24:34.813 回答