【问题标题】:How can I manually set an Angular form field as invalid?如何手动将 Angular 表单字段设置为无效?
【发布时间】:2017-09-19 02:18:02
【问题描述】:

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

模板:

<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。这些都不会导致输入显示其无效状态。

【问题讨论】:

  • 您的后端是否与 Angular 不同?如果是这样,这可能是一个 CORS 问题。你用什么框架做后端。
  • 您可以使用setErros 方法。提示:您应该在组件文件中添加所需的验证器。还有将 ngModel 与反应形式一起使用的特定原因吗?
  • @developer033 在这里聚会有点晚了,但那些看起来不像反应式表单,而是模板驱动的表单。

标签: validation angular angular2-forms


【解决方案1】:

在组件中:

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>

【讨论】:

  • 然后你如何消除错误? setErrors({'incorrect': false})setErrrors({}) 不适合我
  • 我可以将整个响应式表单设置为有效或无效,而不是重置字段吗?
  • @Robouste 您可以通过setErrrors(null)手动删除错误
  • 除了这个答案:没有formData.form.controls['email'].markAsTouched();,这个代码对我不起作用,正如下面提到的@M.Farahmand。使用setErrors({'incorrect': true}) 只需设置ng-invalid css 类作为输入。我希望它可以帮助某人。
  • 如果有更多的验证器,比如 "required" - setErrors(null) 会删除那个错误吗?
【解决方案2】:

添加到 Julia Passynkova 的答案

在组件中设置验证错误:

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

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

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

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

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

【讨论】:

  • 是否可以使用 formData.form.controls['email'].setErrors({'incorrect': false});
  • 反应形式呢?
  • 答案中提到的整个代码是反应形式的完整示例,亲爱的
【解决方案3】:

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

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

【讨论】:

  • 如果实施得当,这个解决方案可以变得非常优雅和快速集成。
【解决方案4】:

我试图在模板表单的 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);
  }
}

这样的陷阱让我更喜欢反应形式。

【讨论】:

  • Cannot find name 'NgModel'.@ViewChild('pwConfirmModel') pwConfirmModel: NgModel; 错误对此问题的任何修复
  • 必须使用 setTimeOuts 是怎么回事?我注意到了这一点,而且控件似乎不会立即更新自己。这引入了很多 hacky 代码来解决这个限制。
  • 谢谢。我知道setErrors,但在我使用setTimeout 之前它不起作用
  • 我建议使用 timer() 运算符而不是 timeout
【解决方案5】:

在我的响应式表单中,如果选中了另一个字段,我需要将一个字段标记为无效。在 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】:

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

    @ViewChild('loginForm') loginForm: NgForm;
    

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

     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});
        });
      }
    

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

    this.loginForm.controls['email'].setErrors(null);
    

    【讨论】:

      【解决方案7】:

      这是一个有效的例子:

      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] ]
        });
      }
      

      【讨论】:

      • 这可能是“hacky”,但我喜欢它,因为您不必设置自定义 ErrorStateMatcher 来处理 Angular Material Input 错误!
      【解决方案8】:

      虽然它迟到但以下解决方案对我有用。

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

      【讨论】:

      • 这很棒!刚刚更新了我的表单错误组件以相应地处理自定义backend.message 字符串:)
      【解决方案9】:

      对于单元测试:

      spyOn(component.form, 'valid').and.returnValue(true);
      

      【讨论】:

        猜你喜欢
        • 2018-09-25
        • 2018-07-08
        • 1970-01-01
        • 2018-05-15
        • 2014-08-27
        • 2018-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多