首頁 > web前端 > js教程 > 主體

angular表單校驗方法

一个新手
發布: 2017-10-17 10:26:02
原創
1894 人瀏覽過

範本

<form id="login-form" class="login-from" #registerForm="ngForm" (ngSubmit)="doSubmit(registerForm.value)">
        <mat-form-field>
          <input matInput placeholder="邮箱" id="email" name="email" [(ngModel)]="formData.email" required pattern="[\w]+?@[\w]+?\.[a-z]+?">
          <mat-error *ngIf="formErrors.email">{{ formErrors.email }}</mat-error>
        </mat-form-field>

        <fieldset ngModelGroup="passwordGroup" #passwordGroup="ngModelGroup" aria-required="true">
          <mat-form-field>
            <input matInput placeholder="密码" type="password" id="password" name="password" [(ngModel)]="formData.password" #password="ngModel"  required minlength="8">
            <!-- <mat-icon matSuffix (click)="hide = !hide">{{hide ? &#39;visibility&#39; : &#39;visibility_off&#39;}}</mat-icon> -->
          </mat-form-field>

          <mat-form-field>
            <!--使用自定义的校验器,加入repeatPassword指令,传入第一个密码输入框的ngModel,即用#password1="ngModel"声明的password1-->
            <input matInput placeholder="确认密码" type="password" id="passwordConfirm" name="passwordConfirm" [(ngModel)]="formData.passwordConfirm" [repeatPassword]="password" >
            <!-- <mat-icon matSuffix (click)="hide = !hide">{{hide ? &#39;visibility&#39; : &#39;visibility_off&#39;}}</mat-icon> -->
            <mat-error *ngIf="formErrors[&#39;passwordGroup.passwordConfirm&#39;]">{{ formErrors[&#39;passwordGroup.passwordConfirm&#39;] }}</mat-error>
          </mat-form-field>
        </fieldset>

        <button class="w-100p" mat-raised-button [disabled] = "!registerForm.valid" >注册</button>
      </form>
登入後複製

元件

import { Component, OnInit ,ViewChild, AfterViewInit } from &#39;@angular/core&#39;;import {NgForm} from "@angular/forms";import { Router } from &#39;@angular/router&#39;;@Component({
  selector: &#39;app-register&#39;,
  templateUrl: &#39;./register.component.html&#39;,
  styleUrls: [&#39;./register.component.css&#39;]
})
export class RegisterComponent implements OnInit {

  ngAfterViewInit(): void {    //订阅表单值改变事件
    this.registerForm.valueChanges.subscribe(data => this.onValueChanged(data));
  }  //找到表单
  @ViewChild(&#39;registerForm&#39;) registerForm: NgForm;

  formData = {} as any;

  doSubmit(obj: any) {    //表单提交
    console.log(JSON.stringify(obj));
  }

  onValueChanged(data) {    
  for (const field in this.formErrors) {      
  this.formErrors[field] = &#39;&#39;;      //取到表单字段
      const control = this.registerForm.form.get(field);      //表单字段已修改或无效
      if (control && control.dirty && !control.valid) {        //取出对应字段可能的错误信息
        const messages = this.validationMessages[field];        //从errors里取出错误类型,再拼上该错误对应的信息
        for (const key in control.errors) {          this.formErrors[field] += messages[key] + &#39;&#39;;
        }
      }

    }

  }  //存储错误信息
  formErrors = {    &#39;email&#39;: &#39;&#39;,    &#39;passwordGroup.password&#39;:&#39;&#39;,    &#39;passwordGroup.passwordConfirm&#39;:&#39;&#39;
  };  //错误对应的提示
  validationMessages = {    &#39;email&#39;: {      &#39;required&#39;: &#39;邮箱必须填写.&#39;,      &#39;pattern&#39;: &#39;邮箱格式不对&#39;,
    },    &#39;passwordGroup.password&#39;:{      &#39;required&#39;: &#39;请输入密码&#39;,      &#39;minlength&#39;: &#39;密码太短&#39;,
    },    &#39;passwordGroup.passwordConfirm&#39;:{      &#39;required&#39;: &#39;请重复输入密码&#39;,      &#39;minlength&#39;: &#39;密码太短&#39;,      &#39;passwordNEQ&#39;:&#39;两次输入密码不同&#39;,      &#39;passwordInValid&#39;:&#39;&#39;
    },

  };

  constructor(private router : Router) { }

  ngOnInit() {
  }

  gotoLogin(){    this.router.navigate([&#39;user/login&#39;]);
  }

  recoverPwd(){    this.router.navigate([&#39;/user/recover/pwd&#39;]);
  }
}
登入後複製

自訂校驗器:repeat-password

import {Directive, Input, OnChanges, SimpleChanges} from &#39;@angular/core&#39;;import {NG_VALIDATORS, FormControl, Validator, AbstractControl, ValidatorFn, NgModel} from "@angular/forms";@Directive({
  selector: &#39;[repeatPassword]&#39;,
  providers: [{provide: NG_VALIDATORS, useExisting: RepeatPasswordDirective, multi: true}]
})
export class RepeatPasswordDirective implements Validator,OnChanges {

  /**
   * 校验方法
   * @param c
   * @returns {{[p: string]: any}}
   */
  validate(c: AbstractControl): {[p: string]: any} {    
  return verifyPassword(c,this.repeatPassword.control);
  }

  ngOnChanges(changes: SimpleChanges): void {      
  this.repeatPassword=changes[&#39;repeatPassword&#39;].currentValue;
  }  /**
   * 通过属性传入另一个input标签的model
   * 名称与选择器一致,就不需要在使用的时候加额外的属性传入
   */
  @Input() repeatPassword:NgModel;

  constructor() { }


}/**
 * 导出校验方法,供响应式表单使用
 * @param passwordController
 * @returns {(currentControl:AbstractControl)=>{[p: string]: any}}
 */export function repeatPassword(passwordController:FormControl):ValidatorFn {  return (currentControl: AbstractControl): {[key: string]: any} => {    return verifyPassword(currentControl,passwordController);
  };
}

function verifyPassword(currentControl: AbstractControl,passwordController:FormControl):{[key: string]: any} {    if(!passwordController.valid) {
      console.log("密码1无效");      return {passwordInValid:{&#39;errorMsg&#39;:&#39;&#39;}}
    }    if((!currentControl.untouched||currentControl.dirty)&&passwordController.value!=currentControl.value) {      return {passwordNEQ:{&#39;errorMsg&#39;:&#39;两次密码输入不一致!&#39;}}
    }
}
登入後複製

注意:
angular表單校驗方法

出現上圖錯誤是因為建立指令時使用:ng g directive repeatPassword
指令,自動加入了前綴app

@Directive({  
selector: &#39;[appRepeatPassword]&#39;,  
providers: [{provide: NG_VALIDATORS, 
useExisting: RepeatPasswordDirective,
multi: true}]
})
登入後複製

改為repeatPassword即可
angular表單校驗方法

出現上圖片錯誤是由於

<input matInput placeholder="密码" type="password" id="password" name="password" [(ngModel)]="formData.password" #password1="ngModel"  required minlength="8">
使用的字段是password,(不知道怎么描述)却是#password1。
登入後複製

改為#password即可

以上是angular表單校驗方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!