How can I manually set an Angular form field as invalid?

后端 未结 9 1644
野的像风
野的像风 2020-11-28 01:58

I am working on a login form and if the user enters invalid credentials we want to mark both the email and password fields as invalid and display a message that says the log

相关标签:
9条回答
  • 2020-11-28 02:39

    I was trying to call setErrors() inside a ngModelChange handler in a template form. It did not work until I waited one tick with setTimeout():

    template:

    <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>
    

    component:

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

    Gotchas like this are making me prefer reactive forms.

    0 讨论(0)
  • 2020-11-28 02:39

    In my Reactive form, I needed to mark a field as invalid if another field was checked. In ng version 7 I did the following:

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

    So above, when I check the box it sets the dropdown as required and marks it as dirty. If you don't mark as such it then it won't be invalid (in error) until you try to submit the form or interact with it.

    If the checkbox is set to false (unchecked) then we clear the required validator on the dropdown and reset it to a pristine state.

    Also - remember to unsubscribe from monitoring field changes!

    0 讨论(0)
  • 2020-11-28 02:47

    in component:

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

    and in HTML:

    <input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email"  #email="ngModel">
    <div *ngIf="!email.valid">{{email.errors| json}}</div>
    
    0 讨论(0)
提交回复
热议问题