Angular 2自定义验证器如何设置control.valid true?

时间:2016-04-14 10:07:48

标签: javascript angularjs typescript angular

我有这样的自定义验证器:

static isEmail(control:Control):{[key:string]:boolean} {
  let emailRegExp = new RegExp("^[-a-z0-9~!$%^&*_=+}{'?]+(.[-a-z0-9~!$%^&*_=+}{'?]+)*@([a-z0-9_][-a-z0-9_]*(.[-a-z0-9_]+)*.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(:[0-9]{1,5})?$", 'i');
  if (control.value.match(emailRegExp)) {
    return {isEmail: true};
  }
  return {isEmail: false};
}

在组件中使用它:

loginForm:ControlGroup;

constructor(private _router:Router,
          private _loginService:LoginService,
          private _formBuilder:FormBuilder) {
this.loginForm = _formBuilder.group({
  email: ['', Validators.compose([
    Validators.required,
    Validators.minLength(8),
    FormValidationService.isEmail
  ])],
  password: ['', Validators.compose([
    Validators.required,
    Validators.minLength(8),
    Validators.maxLength(30),
    FormValidationService.isPassword
  ])]
 });
}

模板:

 <form id="login-form" role="form" [ngFormModel]="loginForm" (ngSubmit)="onLoginSubmit()">
    <div class="form-group">
      <label class="control-label" for="loginFormEmail">Email</label>
      <input type="text" id="loginFormEmail" class="form-control"
             ngControl="email" #email="ngForm">
      <div *ngIf="email.dirty && !email.valid">
        <div class="alert alert-danger" role="alert" [hidden]="!email.errors.minlength">
          Email field must have more then 8 characters
        </div>
        <div class="alert alert-danger" role="alert" [hidden]="email.errors.isEmail">
          Email not valid
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label" for="loginFormPassword">Password</label>
      <input type="password" id="loginFormPassword" class="form-control"
             ngControl="password" #password="ngForm">
      <div *ngIf="password.dirty && !password.valid">
        <div class="alert alert-danger" role="alert" [hidden]="!password.errors.minlength">
          Password field must have more then 8 characters
        </div>
        <div class="alert alert-danger" role="alert" [hidden]="!password.errors.maxlength">
          Password field must have no more then 30 characters
        </div>
        <div class="alert alert-danger" role="alert" [hidden]="password.errors.isPassword">
          Password must meet the following rules:
          <ul>
            <li>At least one upper case english letter</li>
            <li>At least one lower case english letter</li>
            <li>At least one digit</li>
            <li>At least one special character</li>
          </ul>
        </div>
      </div>
    </div>
    <p>If you forgot your password you can <a (click)="toForgot()">reset it</a>.</p>
    <div class="form-group">
      <button type="submit" class="btn btn-primary btn-block" [disabled]="!loginForm.valid">Login</button>
    </div>
  </form>

如果您查看屏幕截图,您可以看到自定义验证程序返回我的值。但无论其值控制如何。有效总是为false,因此表示无效。

enter image description here

我尝试设置control.valid = true,但此字段只有getter。

3 个答案:

答案 0 :(得分:1)

我找到了答案。当控制值有效时,您必须在自定义验证器中返回null:

static isPassword(control:Control):{[key:string]:boolean} {
  let passwordRegExp = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$");
  if (control.value.match(passwordRegExp)) {
    return null;
  }
  return {isPassword: false};
}

答案 1 :(得分:0)

我认为您需要将ngControlGroup添加到包装元素中,否则表单不会跟踪包含的输入元素

<div class="form-group" ngControlGroup="someName">

另见NgControlGroup

答案 2 :(得分:0)

使用FormBuilder类将内联表单定义与JS代码中的ngForm和定义混合。

您应该以这种方式重构输入定义以使用ngFormControl指令:

<input [ngFomControl]="loginForm.controls.password" .../>