我想只使用材料组件执行密码和确认密码验证,如果confirm password field doesn't match
和if it is empty
.Tried许多资源无法实现,则在确认密码字段下面显示错误消息。
也试过this video。
这是我正在寻找的材料成分
HTML
<mat-form-field >
<input matInput placeholder="New password" [type]="hide ? 'password'
: 'text'" [formControl]="passFormControl" required>
<mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' :
'visibility_off'}}</mat-icon>
<mat-error *ngIf="passFormControl.hasError('required')">
Please enter your newpassword
</mat-error>
</mat-form-field>
<mat-form-field >
<input matInput placeholder="Confirm password" [type]="hide ?
'password' : 'text'" [formControl]="confirmFormControl"
required>
<mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' :
'visibility_off'}}</mat-icon>
<mat-error *ngIf="confirmFormControl.hasError('required')">
Confirm your password
</mat-error>
</mat-form-field>
TS
import {Component, OnInit } from '@angular/core';
import {FormControl, FormGroupDirective, NgForm, Validators} from
'@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';
@Component({
selector: 'asd-set-pass',
templateUrl: './set-pass.component.html',
styleUrls: ['./set-pass.component.css']
})
passFormControl = new FormControl('', [
Validators.required,
]);
confirmFormControl = new FormControl('', [
Validators.required,
]);
hide =true;
}
它正在验证以下条件:1)如果密码和确认密码字段为空,则显示错误文本。
我想比较(.ts)文件中的字段,比如它如何验证空字段,以及如果确认密码字段为空则会出现错误。
这个问题可以通过这两个答案的组合来解决:https://stackoverflow.com/a/43493648/6294072和https://stackoverflow.com/a/47670892/6294072
首先,您需要一个自定义验证器来检查密码,它们可能如下所示:
checkPasswords(group: FormGroup) { // here we have the 'passwords' group
let pass = group.controls.password.value;
let confirmPass = group.controls.confirmPass.value;
return pass === confirmPass ? null : { notSame: true }
}
并且您将为您的字段创建一个表单组,而不只是两个表单控件,然后为您的表单组标记该自定义验证器:
this.myForm = this.fb.group({
password: ['', [Validators.required]],
confirmPassword: ['']
}, {validator: this.checkPasswords })
然后如其他答案所述,mat-error
仅显示FormControl是否无效,因此您需要一个错误状态匹配器:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
const invalidParent = !!(control && control.parent && control.parent.invalid && control.parent.dirty);
return (invalidCtrl || invalidParent);
}
}
在上面你可以调整何时显示错误信息。我只会在触摸password
字段时显示消息。另外我想在上面,从required
字段中删除confirmPassword
验证器,因为如果密码不匹配,表单无论如何都无效。
然后在组件中,创建一个新的ErrorStateMatcher
:
matcher = new MyErrorStateMatcher();
最后,模板看起来像这样:
<form [formGroup]="myForm">
<mat-form-field>
<input matInput placeholder="New password" formControlName="password" required>
<mat-error *ngIf="myForm.hasError('required', 'password')">
Please enter your new password
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Confirm password" formControlName="confirmPassword" [errorStateMatcher]="matcher">
<mat-error *ngIf="myForm.hasError('notSame')">
Passwords do not match
</mat-error>
</mat-form-field>
</form>
以下是使用上述代码的演示:StackBlitz
我是这样做的。希望这会帮助你。
HTML:
<form [formGroup]='addAdminForm'>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Password</label>
<div class="col-sm-7">
<input type="password" class="form-control" formControlName='password' (keyup)="checkPassSame()">
<div *ngIf="addAdminForm.controls?.password?.invalid && addAdminForm.controls?.password.touched">
<p *ngIf="addAdminForm.controls?.password?.errors.required" class="errorMsg">*This field is required.</p>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Confirm Password</label>
<div class="col-sm-7">
<input type="password" class="form-control" formControlName='confPass' (keyup)="checkPassSame()">
<div *ngIf="addAdminForm.controls?.confPass?.invalid && addAdminForm.controls?.confPass.touched">
<p *ngIf="addAdminForm.controls?.confPass?.errors.required" class="errorMsg">*This field is required.</p>
</div>
<div *ngIf="passmsg != '' && !addAdminForm.controls?.confPass?.errors?.required">
<p class="errorMsg">*{{passmsg}}</p>
</div>
</div>
</div>
</form>
TS档案:
export class AddAdminAccountsComponent implements OnInit {
addAdminForm: FormGroup;
password: FormControl;
confPass: FormControl;
passmsg: string;
constructor(
private http: HttpClient,
private router: Router,
) {
}
ngOnInit() {
this.createFormGroup();
}
// |---------------------------------------------------------------------------------------
// |------------------------ form initialization -------------------------
// |---------------------------------------------------------------------------------------
createFormGroup() {
this.addAdminForm = new FormGroup({
password: new FormControl('', [Validators.required]),
confPass: new FormControl('', [Validators.required]),
})
}
// |---------------------------------------------------------------------------------------
// |------------------------ Check method for password and conf password same or not -------------------------
// |---------------------------------------------------------------------------------------
checkPassSame() {
let pass = this.addAdminForm.value.password;
let passConf = this.addAdminForm.value.confPass;
if(pass == passConf && this.addAdminForm.valid === true) {
this.passmsg = "";
return false;
}else {
this.passmsg = "Password did not match.";
return true;
}
}
}
最简单的方式imo:
(它也可以用于电子邮件)
public static matchValues(
matchTo: string // name of the control to match to
): (AbstractControl) => ValidationErrors | null {
return (control: AbstractControl): ValidationErrors | null => {
return !!control.parent &&
!!control.parent.value &&
control.value === control.parent.controls[matchTo].value
? null
: { isMatching: false };
};
}
在您的组件中:
this.SignUpForm = this.formBuilder.group({
password: [undefined, [Validators.required]],
passwordConfirm: [undefined,
[
Validators.required,
matchValues('password'),
],
],
});
只需执行标准自定义验证器并首先验证表单本身是否已定义,否则将抛出一个错误,表明表单未定义,因为首先它将尝试在构造表单之前运行验证器。
// form builder
private buildForm(): void {
this.changePasswordForm = this.fb.group({
currentPass: ['', Validators.required],
newPass: ['', Validators.required],
confirmPass: ['', [Validators.required, this.passwordMatcher.bind(this)]],
});
}
// confirm new password validator
private passwordMatcher(control: FormControl): { [s: string]: boolean } {
if (
this.changePasswordForm &&
(control.value !== this.changePasswordForm.controls.newPass.value)
) {
return { passwordNotMatch: true };
}
return null;
}
它只检查新密码字段是否与确认密码字段具有相同的值。是一个特定于确认密码字段而不是整个表单的验证器。
您只需要验证this.changePasswordForm
是否已定义,否则在构建表单时会抛出未定义的错误。
它工作得很好,没有创建指令或错误状态匹配器。
您只需使用密码字段值作为确认密码字段的模式。例如 :
<div class="form-group">
<input type="password" [(ngModel)]="userdata.password" name="password" placeholder="Password" class="form-control" required #password="ngModel" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" />
<div *ngIf="password.invalid && (myform.submitted || password.touched)" class="alert alert-danger">
<div *ngIf="password.errors.required"> Password is required. </div>
<div *ngIf="password.errors.pattern"> Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters.</div>
</div>
</div>
<div class="form-group">
<input type="password" [(ngModel)]="userdata.confirmpassword" name="confirmpassword" placeholder="Confirm Password" class="form-control" required #confirmpassword="ngModel" pattern="{{ password.value }}" />
<div *ngIf=" confirmpassword.invalid && (myform.submitted || confirmpassword.touched)" class="alert alert-danger">
<div *ngIf="confirmpassword.errors.required"> Confirm password is required. </div>
<div *ngIf="confirmpassword.errors.pattern"> Password & Confirm Password does not match.</div>
</div>
</div>
如果您不仅仅有密码和验证密码字段。像这样,确认密码字段仅在用户在此字段上写入内容时突出显示错误:
validators.ts
import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
export const EmailValidation = [Validators.required, Validators.email];
export const PasswordValidation = [
Validators.required,
Validators.minLength(6),
Validators.maxLength(24),
];
export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty)
}
}
export function RepeatPasswordValidator(group: FormGroup) {
const password = group.controls.password.value;
const passwordConfirmation = group.controls.passwordAgain.value;
return password === passwordConfirmation ? null : { passwordsNotEqual: true }
}
register.component.ts
import { FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { EmailValidation, PasswordValidation, RepeatPasswordEStateMatcher, RepeatPasswordValidator } from 'validators';
...
form: any;
passwordsMatcher = new RepeatPasswordEStateMatcher;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group ( {
email: new FormControl('', EmailValidation),
password: new FormControl('', PasswordValidation),
passwordAgain: new FormControl(''),
acceptTerms: new FormControl('', [Validators.requiredTrue])
}, { validator: RepeatPasswordValidator });
}
...
register.component.html
<form [formGroup]="form" (ngSubmit)="submitAccount(form)">
<div class="form-content">
<div class="form-field">
<mat-form-field>
<input matInput formControlName="email" placeholder="Email">
<mat-error *ngIf="form.get('email').hasError('required')">
E-mail is mandatory.
</mat-error>
<mat-error *ngIf="form.get('email').hasError('email')">
Incorrect E-mail.
</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-form-field>
<input matInput formControlName="password" placeholder="Password" type="password">
<mat-hint class="ac-form-field-description">Between 6 and 24 characters.</mat-hint>
<mat-error *ngIf="form.get('password').hasError('required')">
Password is mandatory.
</mat-error>
<mat-error *ngIf="form.get('password').hasError('minlength')">
Password with less than 6 characters.
</mat-error>
<mat-error *ngIf="form.get('password').hasError('maxlength')">
Password with more than 24 characters.
</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-form-field>
<input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
<mat-error *ngIf="form.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-checkbox name="acceptTerms" formControlName="acceptTerms">I accept terms and conditions</mat-checkbox>
</div>
</div>
<div class="form-bottom">
<button mat-raised-button [disabled]="!form.valid">Create Account</button>
</div>
</form>
我希望它有所帮助!
我建议使用库ng-form-rules
。它是一个非常棒的库,用于创建所有不同类型的表单,其中验证逻辑与组件分离(并且可重用)。他们有great documentation,examples和video that show a bunch of its functionality。像这样进行验证(检查两个表单控件的相等性)是微不足道的。
你可以check out their README获得一些高级信息和一个基本的例子。
我正在使用角度6,我一直在寻找匹配密码和确认密码的最佳方式。这也可以用于匹配表单中的任何两个输入。我使用了Angular Directives。我一直想用它们
ng g d compare-validators --spec false,我将在你的模块中添加。以下是指令
import { Directive, Input } from '@angular/core';
import { Validator, NG_VALIDATORS, AbstractControl, ValidationErrors } from '@angular/forms';
import { Subscription } from 'rxjs';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[compare]',
providers: [{ provide: NG_VALIDATORS, useExisting: CompareValidatorDirective, multi: true}]
})
export class CompareValidatorDirective implements Validator {
// tslint:disable-next-line:no-input-rename
@Input('compare') controlNameToCompare;
validate(c: AbstractControl): ValidationErrors | null {
if (c.value.length < 6 || c.value === null) {
return null;
}
const controlToCompare = c.root.get(this.controlNameToCompare);
if (controlToCompare) {
const subscription: Subscription = controlToCompare.valueChanges.subscribe(() => {
c.updateValueAndValidity();
subscription.unsubscribe();
});
}
return controlToCompare && controlToCompare.value !== c.value ? {'compare': true } : null;
}
}
现在在您的组件中
<div class="col-md-6">
<div class="form-group">
<label class="bmd-label-floating">Password</label>
<input type="password" class="form-control" formControlName="usrpass" [ngClass]="{ 'is-invalid': submitAttempt && f.usrpass.errors }">
<div *ngIf="submitAttempt && signupForm.controls['usrpass'].errors" class="invalid-feedback">
<div *ngIf="signupForm.controls['usrpass'].errors.required">Your password is required</div>
<div *ngIf="signupForm.controls['usrpass'].errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="bmd-label-floating">Confirm Password</label>
<input type="password" class="form-control" formControlName="confirmpass" compare = "usrpass"
[ngClass]="{ 'is-invalid': submitAttempt && f.confirmpass.errors }">
<div *ngIf="submitAttempt && signupForm.controls['confirmpass'].errors" class="invalid-feedback">
<div *ngIf="signupForm.controls['confirmpass'].errors.required">Your confirm password is required</div>
<div *ngIf="signupForm.controls['confirmpass'].errors.minlength">Password must be at least 6 characters</div>
<div *ngIf="signupForm.controls['confirmpass'].errors['compare']">Confirm password and Password dont match</div>
</div>
</div>
</div>
我希望这个有所帮助
*此解决方案适用于反应型
您可能听说过确认密码称为跨字段验证。虽然我们通常编写的字段级验证器只能应用于单个字段。对于跨字段验证,您可能必须编写一些父级验证程序。特别是确认密码的情况,我宁愿这样做:
this.form.valueChanges.subscribe(field => {
if (field.password !== field.confirm) {
this.confirm.setErrors({ mismatch: true });
} else {
this.confirm.setErrors(null);
}
});
这是模板:
<mat-form-field>
<input matInput type="password" placeholder="Password" formControlName="password">
<mat-error *ngIf="password.hasError('required')">Required</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" placeholder="Confirm New Password" formControlName="confirm">`enter code here`
<mat-error *ngIf="confirm.hasError('mismatch')">Password does not match the confirm password</mat-error>
</mat-form-field>
我在AJT_82的答案中发现了一个错误。由于我没有足够的声誉在AJT_82的答案下发表评论,我必须在这个答案中发布错误和解决方案。
这是错误:
解决方案:在以下代码中:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
const invalidParent = !!(control && control.parent && control.parent.invalid && control.parent.dirty);
return (invalidCtrl || invalidParent);
}
}
将control.parent.invalid
改为control.parent.hasError('notSame')
将解决这个问题。
经过小小的改动,问题解决了。
我的答案非常简单>我已经创建了密码并使用角度6中的模板driiven确认密码验证
我的html文件
<div class="form-group">
<label class="label-sm">Confirm Password</label>
<input class="form-control" placeholder="Enter Password" type="password" #confirm_password="ngModel" [(ngModel)]="userModel.confirm_password" name="confirm_password" required (keyup)="checkPassword($event)" />
<div *ngIf="confirm_password.errors && (confirm_password.dirty||confirm_password.touched||signup.submitted)">
<div class="error" *ngIf="confirm_password.errors.required">Please confirm your password</div>
</div>
<div *ngIf="i" class='error'>Password does not match</div>
</div>
我的打字稿文件
public i: boolean;
checkPassword(event) {
const password = this.userModel.password;
const confirm_new_password = event.target.value;
if (password !== undefined) {
if (confirm_new_password !== password) {
this.i = true;
} else {
this.i = false;
}
}
}
当点击提交按钮时,我检查i的值是真还是假
如果是真的
if (this.i) {
return false;
}
else{
**form submitted code comes here**
}
我用很少的代码将责任委托给Submit事件。
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" (change)="StorePassword($event)" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputConfirmaPassword" class="form-control" (invalid)="GetInvalidMessage($event)"
[pattern]="iPassword" required>
<label for="inputConfirmaPassword">Confirm password</label>
</div>
我在确认输入中创建了一个与密码相同的模式(由于密码输入的更改事件,将密码存储在变量中)。
iPassword: string = null;
StorePassword ( event: any ): void {
this.iPassword = event.target.value != '' ? event.target.value : null;
}
可以通过以下方式自定义错误消息:
GetInvalidMessage ( event: any ): void {
if ( event.target.validity.patternMismatch && event.target.id == 'inputConfirmaPassword' ) {
event.target.setCustomValidity( "Passwords do not match" );
}
}