显示一条消息当密码不匹配 – Angular

huangapple go评论69阅读模式
英文:

Display a message when passwords don't match - Angular

问题

我正在使用Angular创建一个表单,
我添加了一个确认密码字段,并且当密码不匹配时,我想显示一条消息。
我尝试了许多不同的方法,但它不起作用。我在控制台中添加了一条消息,它正常工作。
有人可以帮助我吗?
提前感谢。

HTML

<form [formGroup]="form">
    <div class="form-group flex-container">

        <label for="password">密码</label>
        <input formControlName="password" id="password" 
               type="password" class="form-control">
        <div *ngIf="password?.touched && password?.invalid" class="alert alert-danger">密码是必填项</div>

        <label for="confirmPassword">确认密码</label>
        <input formControlName="confirmPassword" id="confirmPassword" type="password" class="form-control">
        <div *ngIf="confirmPassword?.touched && confirmPassword?.invalid" class="alert alert-danger">请验证您的密码。</div>
        <div *ngIf="form.hasError('confirmPassword', 'validate')" class="alert alert-danger">密码不匹配。</div>

        <button id="submit" [disabled]="form.invalid">确认</button>

    </div>
</form>

TypeScript

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { PasswordValidators } from './password.validators';

@Component({
  selector: 'customer-registration',
  templateUrl: './customer-registration.component.html',
  styleUrls: ['./customer-registration.component.css']
})

export class CustomerRegistrationComponent {
  form = new FormGroup({
    password: new FormControl('', Validators.required),
    confirmPassword: new FormControl('', [Validators.required, PasswordValidators.validate])
  });

  ngOnInit() {
    this.form.setValidators(PasswordValidators.validate);
  }

  get password() {
    return this.form.get('password');
  }

  get confirmPassword() {
    return this.form.get('confirmPassword');
  }   
}
import { AbstractControl, ValidationErrors, FormGroup, ValidatorFn } from '@angular/forms';

export class PasswordValidators {
  static validate(control: AbstractControl): ValidationErrors | null {
    const password = control.get('password')?.value;
    const confirmPassword = control.get('confirmPassword')?.value;

    if (password !== confirmPassword) {
      console.log("密码不匹配");
      return { confirmPassword: true };
    }
    return null;
  }
}
英文:

I am creating a form in Angular,
I added a confirm-password field, and I want to display a message when the passwords do not match.
I have tried many different approaches - but it doesn't work. I added a message in the console and it worked properly.
Can someone please help me with this?
Thanks in advance.

HTML

&lt;form [formGroup]=&quot;form&quot;&gt;
    &lt;div class=&quot;form-group flex-container&quot;&gt;

        &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;
        &lt;input formControlName=&quot;password&quot; id=&quot;password&quot; 
               type=&quot;password&quot; class=&quot;form-control&quot;&gt;
        &lt;div *ngIf=&quot;password?.touched &amp;&amp; password?.invalid&quot; class=&quot;alert alert-danger&quot;&gt;Password is required&lt;/div&gt;

        &lt;label for=&quot;confirmPassword&quot;&gt;Confirm password&lt;/label&gt;
    &lt;input formControlName=&quot;confirmPassword&quot; id=&quot;confirmPassword&quot; type=&quot;password&quot; class=&quot;form-control&quot;&gt;
    &lt;div *ngIf=&quot;confirmPassword?.touched &amp;&amp; confirmPassword?.invalid&quot; class=&quot;alert alert-danger&quot;&gt;Please verify your password.&lt;/div&gt;
   &lt;div *ngIf=&quot;form.hasError(&#39;confirmPassword&#39;, &#39;validate&#39;)&quot; class=&quot;alert alert-danger&quot;&gt;Passwords do not match.&lt;/div&gt;

    &lt;button id=&quot;submit&quot; [disabled]=&quot;form.invalid&quot;&gt;אישור&lt;/button&gt;

&lt;/form&gt;

TypeScript

import { Component } from &#39;@angular/core&#39;;
import { FormGroup, FormControl, Validators } from &#39;@angular/forms&#39;;
import { PasswordValidators } from &#39;./password.validators&#39;;

@Component({
  selector: &#39;customer-registration&#39;,
  templateUrl: &#39;./customer-registration.component.html&#39;,
  styleUrls: [&#39;./customer-registration.component.css&#39;]
})

export class CustomerRegistrationComponent {
  form = new FormGroup({
    password: new FormControl(&#39;&#39;, Validators.required),
    confirmPassword: new FormControl(&#39;&#39;, [Validators.required, PasswordValidators.validate])
  });


  ngOnInit() {
    this.form.setValidators(PasswordValidators.validate);
  }


  get password() {
    return this.form.get(&#39;password&#39;);
  }

  get confirmPassword() {
    return this.form.get(&#39;confirmPassword&#39;);
  }   
import { AbstractControl, ValidationErrors, FormGroup, ValidatorFn } from &#39;@angular/forms&#39;;

export class PasswordValidators {
  static validate(control: AbstractControl): ValidationErrors | null {
    const password = control.get(&#39;password&#39;)?.value;
    const confirmPassword = control.get(&#39;confirmPassword&#39;)?.value;

    if (password !== confirmPassword) {
      console.log(&quot;passwords do not match&quot;);
      return { confirmPassword: true };
      
    }
    return null;
  }
}

答案1

得分: 4

代码中的问题在于您将验证器添加到了单个FormControl元素上,但您试图验证多个FormControls。您的验证器函数只接收confirmPassword FormControl,而不是表单中的其他控件。由于您已经将FormControls放在了一个FormGroup中,您可以将验证器函数添加到FormGroup中。这个函数应该接受一个AbstractControl(它将是FormGroup),并根据需要返回值。看起来您现有的验证器函数应该已经这样做了。

export class CustomerRegistrationComponent {
  form = new FormGroup({
    password: new FormControl('', Validators.required),
    confirmPassword: new FormControl('', Validators.required)
  }, { validator: PasswordValidators.validate });
  // ...
}
英文:

The reason it is not working is because you have your validation on a single FormControl element, but you are attempting to validate multiple FormControls. Your validator function is only receiving the confirmPassword FormControl, not the other controls in the form. Since you already have the FormControls in a FormGroup, you can add a validator function to the FormGroup. This function should accept an AbstractControl (which will be the FormGroup) and can return the value as needed. It looks like your existing validator function should already do this.

export class CustomerRegistrationComponent {
  form = new FormGroup({
    password: new FormControl(&#39;&#39;, Validators.required),
    confirmPassword: new FormControl(&#39;&#39;, Validators.required)
  }, {validator: PasswordValidators.validate});

...
}

huangapple
  • 本文由 发表于 2023年6月1日 00:59:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定