如何手动将Angular表单字段设置为无效?

时间:2017-04-21 23:40:00

标签: validation angular angular2-forms

我正在处理登录表单,如果用户输入无效凭据,我们要将电子邮件和密码字段都标记为无效,并显示一条消息,指出登录失败。如何从可观察的回调中将这些字段设置为无效?

模板:

<form #loginForm="ngForm" (ngSubmit)="login(loginForm)" id="loginForm">
  <div class="login-content" fxLayout="column" fxLayoutAlign="start stretch">
    <md-input-container>
      <input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email">
    </md-input-container>
    <md-input-container>
      <input mdInput placeholder="Password" type="password" name="password" required [(ngModel)]="password">
    </md-input-container>
    <p class='error' *ngIf='loginFailed'>The email address or password is invalid.</p>
    <div class="extra-options" fxLayout="row" fxLayoutAlign="space-between center">
     <md-checkbox class="remember-me">Remember Me</md-checkbox>
      <a class="forgot-password" routerLink='/forgot-password'>Forgot Password?</a>
    </div>
    <button class="login-button" md-raised-button [disabled]="!loginForm.valid">SIGN IN</button>
     <p class="note">Don't have an account?<br/> <a [routerLink]="['/register']">Click here to create one</a></p>
   </div>
 </form>

登录方式:

 @ViewChild('loginForm') loginForm: HTMLFormElement;

 private login(formData: any): void {
    this.authService.login(formData).subscribe(res => {
      alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
    }, error => {
      this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
      this.loginForm.controls.email.invalid = true;
      this.loginForm.controls.password.invalid = true; 
    });
  }

除了将输入无效标志设置为true之外,我还尝试将email.valid标志设置为false,并将loginForm.invalid设置为true。这些都不会导致输入显示无效状态。

9 个答案:

答案 0 :(得分:151)

组件中的

formData.form.controls['email'].setErrors({'incorrect': true});

并在html中:

<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email"  #email="ngModel">
<div *ngIf="!email.valid">{{email.errors| json}}</div>

答案 1 :(得分:56)

添加Julia Passynkova的回答

在组件中设置验证错误:

formData.form.controls['email'].setErrors({'incorrect': true});

取消设置组件中的验证错误:

formData.form.controls['email'].setErrors(null);

小心使用'null'取消设置错误,因为这会覆盖所有错误。如果你想保留一些,你可能必须首先检查是否存在其他错误:

if(isIncorrectOnlyError){
   formData.form.controls['email'].setErrors(null);
}

答案 2 :(得分:15)

我试图在模板表单中的ngModelChange处理程序中调用setErrors()。在我用setTimeout()等待一个勾号之前它没有用。

模板:

<input type="password" [(ngModel)]="user.password" class="form-control" 
 id="password" name="password" required (ngModelChange)="checkPasswords()">

<input type="password" [(ngModel)]="pwConfirm" class="form-control"
 id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
 #pwConfirmModel="ngModel">

<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
   Passwords do not match
</div>

成分:

@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;

checkPasswords() {
  if (this.pwConfirm.length >= this.user.password.length &&
      this.pwConfirm !== this.user.password) {
    console.log('passwords do not match');
    // setErrors() must be called after change detection runs
    setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
  } else {
    // to clear the error, we don't have to wait
    this.pwConfirmModel.control.setErrors(null);
  }
}

这样的事情让我更喜欢反应形式。

答案 3 :(得分:13)

在新版本的材料2中,其控制名称以mat前缀setErrors()开头并不起作用,而Juila的答案可以改为:

formData.form.controls['email'].markAsTouched();

答案 4 :(得分:1)

Here is an example that works:

MatchPassword(AC: FormControl) {
  let dataForm = AC.parent;
  if(!dataForm) return null;

  var newPasswordRepeat = dataForm.get('newPasswordRepeat');
  let password = dataForm.get('newPassword').value;
  let confirmPassword = newPasswordRepeat.value;

  if(password != confirmPassword) {
    /* for newPasswordRepeat from current field "newPassword" */
    dataForm.controls["newPasswordRepeat"].setErrors( {MatchPassword: true} );
    if( newPasswordRepeat == AC ) {
      /* for current field "newPasswordRepeat" */
      return {newPasswordRepeat: {MatchPassword: true} };
    }
  } else {
    dataForm.controls["newPasswordRepeat"].setErrors( null );
  }
  return null;
}

createForm() {
  this.dataForm = this.fb.group({
    password: [ "", Validators.required ],
    newPassword: [ "", [ Validators.required, Validators.minLength(6), this.MatchPassword] ],
    newPasswordRepeat: [ "", [Validators.required, this.MatchPassword] ]
  });
}

答案 5 :(得分:1)

在我的“反应式”表单中,如果选中了另一个字段,则需要将一个字段标记为无效。在ng版本7中,我执行了以下操作:

    const checkboxField = this.form.get('<name of field>');
    const dropDownField = this.form.get('<name of field>');

    this.checkboxField$ = checkboxField.valueChanges
        .subscribe((checked: boolean) => {
            if(checked) {
                dropDownField.setValidators(Validators.required);
                dropDownField.setErrors({ required: true });
                dropDownField.markAsDirty();
            } else {
                dropDownField.clearValidators();
                dropDownField.markAsPristine();
            }
        });

因此,在上面,当我选中该复选框时,它会根据需要设置下拉菜单并将其标记为脏菜单。如果您未将其标记为此类,则在您尝试提交表单或与之交互之前,它不会无效(错误)。

如果该复选框设置为false(未选中),那么我们会清除下拉菜单中所需的验证程序,并将其重置为原始状态。

也-记得退订监视字段更改!

答案 6 :(得分:0)

尽管它很晚但随后的解决方案对我有用。

    let control = this.registerForm.controls['controlName'];
    control.setErrors({backend: {someProp: "Invalid Data"}});
    let message = control.errors['backend'].someProp;

答案 7 :(得分:0)

您还可以将viewChild'type'更改为NgForm,如下所示:

str1

然后以@Julia提到的相同方式引用您的控件:

@ViewChild('loginForm') loginForm: NgForm;

将错误设置为null将清除UI上的错误:

 private login(formData: any): void {
    this.authService.login(formData).subscribe(res => {
      alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
    }, error => {
      this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.

      this.loginForm.controls['email'].setErrors({ 'incorrect': true});
      this.loginForm.controls['password'].setErrors({ 'incorrect': true});
    });
  }

答案 8 :(得分:-2)

对于单元测试:

spyOn(component.form, 'valid').and.returnValue(true);
相关问题