简体   繁体   English

Angular2使用模式进行表单验证

[英]Angular2 form validation with pattern

I'm trying to user the pattern attribute for email in Angular 4.3.0 but the field.errors.pattern returns true even when the email is correct. 我正在尝试在Angular 4.3.0中使用电子邮件的pattern属性,但是即使电子邮件正确, field.errors.pattern也会返回true。 I'm working on an existing code and this pattern was used in this.I'm also not able to understand the RegEx. 我正在处理现有代码,因此使用了这种模式。我也无法理解RegEx。

Below is the HTML form 以下是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>

Below is the pattern 下面是模式

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);

I have encounter the same problem too and I don't know why regex seems not working in my Angular 4 project. 我也遇到了同样的问题,我不知道为什么regex在我的Angular 4项目中似乎不起作用。 I start using Validators in Angular's FormGroup and the email validation works like a charm in my project. 我开始在Angular的FormGroup中使用验证器 ,并且电子邮件验证在我的项目中就像一个魅力一样。

Here's my snippet of code for my Edit Profile Page ( edit-profile.component.html ): 这是我的“编辑配置文件”页面的代码段( 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>

and in the edit-profile.component.ts file: 并在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
    }
  }

Hope this helps! 希望这可以帮助!

Angular 4 has a built-in email validation tag that can be added within the input. Angular 4具有内置的email验证标签,可以将其添加到输入中。 Eg: 例如:

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

This will be valid for a series of numbers and letters then an @ then another series of letters. 这对于一系列数字和字母,然后是@以及另一系列的字母有效。 It will not account for the dot after the @ -- for that you can use the "pattern" tag within the input and your standard regex. 它不会考虑@后面的点,因为您可以在输入和标准正则表达式中使用“模式”标签。

Or if you want to go with pattern try this 或者,如果您想使用模式,请尝试此

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

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

The following should work: 以下应该工作:

 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,}))$/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM