英文:
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
<form [formGroup]="form">
<div class="form-group flex-container">
<label for="password">Password</label>
<input formControlName="password" id="password"
type="password" class="form-control">
<div *ngIf="password?.touched && password?.invalid" class="alert alert-danger">Password is required</div>
<label for="confirmPassword">Confirm password</label>
<input formControlName="confirmPassword" id="confirmPassword" type="password" class="form-control">
<div *ngIf="confirmPassword?.touched && confirmPassword?.invalid" class="alert alert-danger">Please verify your password.</div>
<div *ngIf="form.hasError('confirmPassword', 'validate')" class="alert alert-danger">Passwords do not match.</div>
<button id="submit" [disabled]="form.invalid">אישור</button>
</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("passwords do not match");
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('', Validators.required),
confirmPassword: new FormControl('', Validators.required)
}, {validator: PasswordValidators.validate});
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论