码迷,mamicode.com
首页 > 其他好文 > 详细

Angular 表单校验

时间:2017-08-11 14:33:49      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:cto   png   电话号码   校验   表单   ges   text   input   UI   

1.html

<form [formGroup]="formModel" (submit)="submit()">
   <div>
     用户名:<input  type="text" formControlName="username">
     电话:<input  type="text" formControlName="mobile">

     <div formGroupName="passwordsGroup">
       密码:<input  type="password" formControlName="password">
       确认密码:<input  type="password" formControlName="pconfirm">
     </div>

   </div>
  <div><button type="submit">保存</button></div>
</form>

  

2. 控制器中创建FormModel

  constructor(private http: Http, fb: FormBuilder) {
    this.formModel = fb.group({
      username:  [‘‘, [Validators.required, Validators.minLength(10)]],
      mobile:  [‘‘, this.mobileValidator],
      passwordsGroup: fb.group({
          password:  [‘‘],
          pconfirm: [‘‘]
      }, { validator: this.equalValidator} ),
    });
  }

  

3. 创建自定义校验器

  mobileValidator(control: FormControl): any {
    const myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    const valid = myreg.test(control.value);
    console.log(‘mobile result: ‘ + valid);
    return valid ? null : {mobile: true};

  }

  equalValidator(group: FormGroup): any {
    const password: FormControl = group.get(‘password‘) as FormControl;
    const pconfirm: FormControl = group.get(‘pconfirm‘) as FormControl;
    const valid: boolean = password.value === pconfirm.value;
    console.log(‘password equal: ‘ + valid);
    return valid ? null : {equal: true};
  }

  mobileValidator用来校验电话号码是否有效

  equalValidator 用来校验两次输入的密码是否一致

 

4. submit方法

  submit() {
    const isValid: boolean = this.formModel.get(‘username‘).valid;
    console.log(‘username: ‘ + isValid);
    const errors: any = this.formModel.get(‘username‘).errors;
    console.log(‘username errors‘ + JSON.stringify(errors));
    if ( this.formModel.valid) {
      console.log(this.formModel.value);
    }

  }

  

5.完整的代码 

技术分享

 

Angular 表单校验

标签:cto   png   电话号码   校验   表单   ges   text   input   UI   

原文地址:http://www.cnblogs.com/linlf03/p/7345460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!