美文网首页
6.表单校验下

6.表单校验下

作者: Monee121 | 来源:发表于2018-03-05 12:52 被阅读0次

    新建一个ts,把校验方法放进去,然后导出。移出的方法不是ts 的类的方法,而是全局的ts的函数,需要用function来声明,用export来暴露出去。然后在模板组件里直接引用它。

    Validators.ts(密码验证,手机号验证)

    /*方法*/
    import {FormControl, FormGroup} from '@angular/forms';
    
    export  function mobileValidator(control: FormControl): any {
      const mobieReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
      const valid = mobieReg.test(control.value);
      console.log('mobile的校验结果是:' + valid);
      return valid ? null : {mobile : true}; /*返回空代表通过,valid为false的时候,返回对象,key,随便给一个值*/
    }
    export  function equalValidator(group: FormGroup): any {
      const password: FormControl = group.get('password') as FormControl;
      const confirmpass: FormControl = group.get('confirmpass') as FormControl;
      const valid: boolean = (confirmpass.value === password.value);
      console.log('密码校验结果' + valid);
      return valid ? null : {equal: {descxx: '密码和确认密码不匹配'}};
    }
    
    

    reactive-regist.ts

    export class ReactiveRegistComponent implements OnInit {
      formModel: FormGroup;
    
      constructor(fb: FormBuilder) {
        this.formModel = fb.group({
         /* username: new FormControl(),*/
         username: ['', [Validators.required,  Validators.minLength(6)]], /*必填,最长6*/
          mobile: ['', mobileValidator],
          passwordsGroup: fb.group({
             password: ['' , Validators.minLength(6)],
            confirmpass: ['']
            }, {validator: equalValidator}), /*group的校验这样写*/
        });
      }
      onSubmit() {
      /*  const isValid: boolean = this.formModel.get('username').valid; /!*校验的结果布尔值*!/
        console.log('username的校验结果是:' + isValid);
        const errors: any = this.formModel.get('username').errors; /!*校验结果错误信息*!/
        console.log('username的错误信息是' + JSON.stringify(errors));*/
      if (this.formModel.valid) {/*所有字段合法为true,打印信息*/
        console.log(this.formModel.value);
      }
     }
      ngOnInit() {
      }
    
    }
    
    

    模板

    <form [formGroup]="formModel" (submit)="onSubmit()">
      <div>用户名:<input type="text" name="username" formControlName="username"/></div>
      <div [hidden]="!formModel.hasError('required','username')">
        <!--hasError两个参数,一是校验的是否必填,校验器失败返回的对象的key的值,有值就是失败的
        。二是检查的字段名字,hidden为true隐藏,所以取反。-->
        用户名是必填项
      </div>
      <div>电话:<input type="text" name="mobile" formControlName="mobile"/></div>
      <div [hidden]="!formModel.hasError('mobile','mobile')">请输入正确的手机号</div>
      <div formGroupName="passwordsGroup">
         <div>密码:<input type="text" name="password" formControlName="password"/></div>
        <div [hidden]="!formModel.hasError('minlength',['passwordsGroup','password'])">密码最小长度是6</div>
         <div>确认密码:<input type="text" name="confirmpass" formControlName="confirmpass"/></div>
        <div [hidden]="!formModel.hasError('equal','passwordsGroup')">{{formModel.getError('equal','passwordsGroup')?.descxx}}</div>
      </div>
      <div><input type="submit" value="提交"/></div>
    </form>
    

    异步校验器:可观测的流

    Validators.ts

    export  function mobileAsyncValidator(control: FormControl): any {
      const mobieReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
      const valid = mobieReg.test(control.value);
      console.log('mobile的校验结果是:' + valid);
      return Observable.of(valid ? null : {mobile : true}).delay(5000); /*在返回的时候,返回的是一个流,延迟五秒,模拟服务器,五秒以后返回*/
    } /*异步校验器可作为fromcontrol的第三个构造函数*/
    

    表单.ts

      mobile: ['', mobileValidator, mobileAsyncValidator], /*异步手机号的校验*/
    

    模板

    <div>{{formModel.status}}</div><!--表单的状态-->
    

    相关文章

      网友评论

          本文标题:6.表单校验下

          本文链接:https://www.haomeiwen.com/subject/kimqfftx.html