- 首页
- 前端开发
- 用于密码的反应形式的自定义验证器并确认密码匹配将未定义的参数导入 Angular 4
用于密码的反应形式的自定义验证器并确认密码匹配将未定义的参数导入 Angular 4
[英] Custom Validator on reactive form for password and confirm password matching getting undefined parameters into Angular 4
本文介绍了用于密码的反应形式的自定义验证器并确认密码匹配将未定义的参数导入 Angular 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试实现一个自定义验证器来检查密码和密码确认是否相同.问题是验证器正在获取未定义的密码和confirmedPassword 参数.我如何使这项工作.如果我将条件更改为 === 而不是 !== 它会在字段相同时正确抛出错误,因此该函数会起作用.有谁知道这里的错误是什么?
signup.component.html
<div class="block"><div class="well"><form (onSubmit)="onSubmit()" [formGroup]="signUpForm"><div class="form-group"><label for="username" class="control-label">惯用名称:</label><input type="text" class="form-control" formControlName="username" title="请输入您的用户名" placeholder="username"><p class="help-block" *ngIf="signUpForm.get('username').hasError('required') && signUpForm.get('username').touched">El nombre de usuarioes obligatorio </p><p class="help-block" *ngIf="signUpForm.get('username').hasError('minlength') && signUpForm.get('username').touched">El nombre de usuariodebe tener al menos 6 caracteres</p><p class="help-block" *ngIf="signUpForm.get('username').hasError('maxlength') && signUpForm.get('username').touched">El nombre de usuariodebe tener menos de 15 caracteres</p>
<div class="form-group"><label for="email" class="control-label">电子邮件:</label><input class="form-control" formControlName="email" title="请输入您的邮箱" placeholder="example@gmail.com"><p class="help-block" *ngIf="signUpForm.get('email').hasError('required') && signUpForm.get('email').touched">电子邮件方向es 强制性的</p><p class="help-block" *ngIf="signUpForm.get('email').hasError('email') && signUpForm.get('email').touched">Debe ingresar una direcciónde correo valida</p>
<div class="form-group"><label for="password" class="control-label">Contraseña:</label><input type="password" class="form-control" formControlName="password" title="请输入您的密码" [(ngModel)]="password"><p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña<;/p>
<div class="form-group"><label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label><input type="password" class="form-control" formControlName="confirmedPassword" title="请重新输入密码" [(ngModel)]="confirmedPassword"><p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">La confirmación de contraseñano puede estar vacía</p><p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">Las contraseñas 并非巧合</p>
<button type="submit" class="btn btn-success" [disabled]="!signUpForm.valid">Registrarse</button><a routerLink="/signin" class="btn btn-default" style="">Ya tenes usuario?洛格特</a>{{ 创建消息 }}</表单>
signup.component.ts
import { Component, OnInit, ViewChild, Input } from '@angular/core';从@angular/forms"导入 { FormControl, FormGroup, Validators };从'../../shared/custom-validators'导入{CustomValidators};从 'rxjs/Observable' 导入 { Observable };@成分({选择器:'应用程序注册',templateUrl: './signup.component.html',styleUrls: ['./signup.component.sass']})导出类 SignupComponent 实现 OnInit {注册表格:表格组;用户 = {用户名: '',电子邮件: '',密码: ''};提交=假;@Input() 密码='';@Input() 确认密码='';构造函数(){}ngOnInit() {this.signUpForm = new FormGroup({'username': new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(5)]),'密码': new FormControl(null, [Validators.required]),'confirmedPassword': new FormControl(null, [Validators.required, CustomValidators.passwordsMatch(this.password,this.confirmedPassword).bind(this)])});}提交(){如果(this.signUpForm.valid){console.log(this.signUpForm.value);}}}
custom-validators.ts
import { FormControl } from '@angular/forms';导出类 CustomValidators{公共静态密码匹配(密码:字符串,确认密码:字符串){return (control: FormControl) : { [s: string]: boolean } =>{//获取两个变量的未定义值控制台日志(密码,确认密码);//如果我将此条件更改为 === 它会抛出错误,如果//两个字段相同,所以这部分有效如果(密码!== 确认密码){返回{'密码不匹配':真}} 别的 {//无论如何它总是到达这里返回空;}}}}
解决方案
从
导入{AbstractControl、FormBuilder、FormGroup、Validators}
设置您的密码输入组,无需使用ngModel".
<div class="form-group"><label for="password" class="control-label">Contraseña:</label><input type="password" class="form-control" formControlName="password" title="请输入密码"><p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña<;/p>
<div class="form-group"><label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label><input type="password" class="form-control" formControlName="confirmedPassword" title="请重新输入密码"><p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">必须输入密码<;/p><p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">密码不匹配<;/p>
buildForm(): void {this.userForm = this.formBuilder.group({密码:this.formBuilder.group({密码:['', [Validators.required]],Confirm_password: ['', [Validators.required]],}, {validator: this.passwordConfirming}),});}
<块引用>
添加此自定义功能用于验证密码和确认密码
passwordConfirming(c: AbstractControl): { invalid: boolean } {if (c.get('password').value !== c.get('confirm_password').value) {返回{无效:真};}}
<块引用>
密码不匹配时显示错误
<div style='color:#ff7355' *ngIf="userForm.get(['passwords','password']).value != userForm.get(['passwords','confirm_password']).value && userForm.get(['passwords','confirm_password']).value != null">密码不匹配
I'm trying to implement a custom validator to check if the password and password confirm are equal. The problem is that the validator is getting undefined password and confirmedPassword parameters. How do I make this work. The function works cause if I change the condition to === instead of !== it throws the error correctly when the fields are the same. Does anyone know which is the error here?
signup.component.html
<div class="col-md-7 col-md-offset-1 col-sm-7">
<div class="block">
<div class="well">
<form (onSubmit)="onSubmit()" [formGroup]="signUpForm">
<div class="form-group">
<label for="username" class="control-label">Nombre de usuario:</label>
<input type="text" class="form-control" formControlName="username" title="Please enter your username" placeholder="username">
<p class="help-block" *ngIf="signUpForm.get('username').hasError('required') && signUpForm.get('username').touched">El nombre de usuario es obligatorio</p>
<p class="help-block" *ngIf="signUpForm.get('username').hasError('minlength') && signUpForm.get('username').touched">El nombre de usuario debe tener al menos 6 caracteres</p>
<p class="help-block" *ngIf="signUpForm.get('username').hasError('maxlength') && signUpForm.get('username').touched">El nombre de usuario debe tener menos de 15 caracteres</p>
</div>
<div class="form-group">
<label for="email" class="control-label">E-mail:</label>
<input class="form-control" formControlName="email" title="Please enter your email" placeholder="example@gmail.com">
<p class="help-block" *ngIf="signUpForm.get('email').hasError('required') && signUpForm.get('email').touched">La dirección de email es obligatoria</p>
<p class="help-block" *ngIf="signUpForm.get('email').hasError('email') && signUpForm.get('email').touched">Debe ingresar una dirección de correo válida</p>
</div>
<div class="form-group">
<label for="password" class="control-label">Contraseña:</label>
<input type="password" class="form-control" formControlName="password" title="Please enter your password" [(ngModel)]="password">
<p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
</div>
<div class="form-group">
<label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
<input type="password" class="form-control" formControlName="confirmedPassword" title="Please re-enter your password" [(ngModel)]="confirmedPassword">
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">La confirmación de contraseña no puede estar vacía</p>
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">Las contraseñas no coinciden</p>
</div>
<button type="submit" class="btn btn-success" [disabled]="!signUpForm.valid">Registrarse</button>
<a routerLink="/signin" class="btn btn-default" style="">Ya tenes usuario? Logueate</a> {{ creationMessage }}
</form>
</div>
</div>
</div>
signup.component.ts
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { CustomValidators } from '../../shared/custom-validators';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.sass']
})
export class SignupComponent implements OnInit {
signUpForm: FormGroup;
user = {
username: '',
email: '',
password: ''
};
submitted = false;
@Input() password='';
@Input() confirmedPassword='';
constructor() { }
ngOnInit() {
this.signUpForm = new FormGroup({
'username': new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(5)]),
'password': new FormControl(null, [Validators.required]),
'confirmedPassword': new FormControl(null, [Validators.required, CustomValidators.passwordsMatch(this.password,this.confirmedPassword).bind(this)])
});
}
onSubmit() {
if (this.signUpForm.valid) {
console.log(this.signUpForm.value);
}
}
}
custom-validators.ts
import { FormControl } from '@angular/forms';
export class CustomValidators{
public static passwordsMatch(password: string, confirmedPassword: string) {
return (control: FormControl) : { [s: string]: boolean } =>{
//getting undefined values for both variables
console.log(password,confirmedPassword);
//if I change this condition to === it throws the error if the
// two fields are the same, so this part works
if (password !== confirmedPassword) {
return { 'passwordMismatch': true }
} else {
//it always gets here no matter what
return null;
}
}
}
}
解决方案
import {AbstractControl, FormBuilder, FormGroup, Validators} from
set your password input into the group and no need to use "ngModel".
<div class="form-group row" formGroupName="passwords">
<div class="form-group">
<label for="password" class="control-label">Contraseña:</label>
<input type="password" class="form-control" formControlName="password" title="Please enter your password">
<p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
</div>
<div class="form-group">
<label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
<input type="password" class="form-control" formControlName="confirmedPassword" title="Please re-enter your password">
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">Password must be required</p>
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">password does not match</p>
</div>
buildForm(): void {
this.userForm = this.formBuilder.group({
passwords: this.formBuilder.group({
password: ['', [Validators.required]],
confirm_password: ['', [Validators.required]],
}, {validator: this.passwordConfirming}),
});
}
add this custom function for validate password and confirm password
passwordConfirming(c: AbstractControl): { invalid: boolean } {
if (c.get('password').value !== c.get('confirm_password').value) {
return {invalid: true};
}
}
Display error when password does not match
<div style='color:#ff7355' *ngIf="userForm.get(['passwords','password']).value != userForm.get(['passwords','confirm_password']).value && userForm.get(['passwords','confirm_password']).value != null">
Password does not match</div>
这篇关于用于密码的反应形式的自定义验证器并确认密码匹配将未定义的参数导入 Angular 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文