我正在尝试创建一个密码重置表单,我需要为新密码创建两个字段并确认新密码。我正在测试它们是否相同或者在angular2中使用自定义验证,但我的代码不起作用。我在这里附上我的组件文件和自定义验证类,任何人都可以建议我什么是适当的解决方案。
我正在使用角度2.4
组件代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
import { Checkpassword } from '../checkpassword';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
signUpForm: FormGroup;
constructor(fb: FormBuilder) {
this.signUpForm = fb.group({
oldpassword: ['', Validators.compose([
Validators.required,
Checkpassword.checkPasswordLength
])],
newpassword1: ['', Validators.required],
newpassword2: ['', Validators.required]
}, {validator: Checkpassword.isSamePassword});
}
ngOnInit() {
}
}
自定义验证码:
import { FormControl, FormGroup } from '@angular/forms'
export class Checkpassword {
static checkPasswordLength(control: FormControl){
if(control.value.length > 0 && control.value.length < 5 ) return {smallPassword: true};
return null;
}
static isSamePassword(group: FormGroup){
let newpassword1 = group.controls['newpassword1'].value;
let newpassword2 = group.controls['newpassword2'].value;
if(newpassword1 !== newpassword2){
return {notSamePassword: true};
}
return null;
}
}
答案 0 :(得分:7)
如果你正在使用ngModel,你可以使用模式并引用已输入的密码。
pattern={{user[0].password}}
完整代码:
<label>Password:</label>
<input type="text" name="password" #password="ngModel" minlength="6" required [(ngModel)]="user[0].password">
<div *ngIf="password.errors && (password.dirty || password.touched)"class="alert-error">
<div [hidden]="!email.errors.required">
Password is required!
</div>
<div [hidden]="!email.errors.minlength">
Password must be at least 6 characters or longer.
</div>
</div>
<br>
<label>Confirm password:</label>
<input type="text" name="repassword" #repassword="ngModel" minlength="6" pattern={{user[0].password}} required [(ngModel)]="user[0].repassword">
<div *ngIf="repassword.errors && (repassword.dirty || repassword.touched)" class="alert-error">
<div [hidden]="!repassword.errors.required">
Please confirm the password.
</div>
<div [hidden]="!repassword.errors.minlength">
Password must be at least 6 characters or longer.
</div>
<div [hidden]="!repassword.errors.pattern">
Passwords must match.
答案 1 :(得分:1)
您的验证器函数将一个组作为参数,但您只将验证器分配给一个控件。要解决您的问题,您应该在同一个组件中使用它并传递两个参数,如下所示
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
signUpForm: FormGroup;
constructor(fb: FormBuilder) {
this.signUpForm = fb.group({
oldpassword: ['', Validators.compose([
Validators.required,
Checkpassword.checkPasswordLength
])],
newpassword1: ['', Validators.required],
newpassword2: ['', Validators.required]
//////////////////////////////////////////////////////////////////////////
}, {validator: this.isSamePassword(newpassword1,newpassword2});
//////////////////////////////////////////////////////////////////////////
}
ngOnInit() {
}
//////////////////////////////////////////////////////////////////////////
private isSamePassword(newpassword1 : FormControl, newpassword1 : FormControl):{[key: string]:any}{
if(newpassword1 !== newpassword2){
return {'notSamePassword': true};
}
return null;
}
//////////////////////////////////////////////////////////////////////////
}
注意:函数的返回类型和notSamePassword
应该用引号括起来
答案 2 :(得分:0)
将这些添加到app.module.ts文件中以使用反应形式
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
],
declarations: [
AppComponent
]
providers: [],
bootstrap: [
AppComponent
]
})
export class AppModule {}
import { Component,OnInit } from '@angular/core';
import template from './add.component.html';
import { FormGroup,FormBuilder,Validators } from '@angular/forms';
import { matchingPasswords } from './validators';
@Component({
selector: 'app',
template
})
export class AppComponent implements OnInit {
addForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
}
ngOnInit() {
this.addForm = this.formBuilder.group({
username: ['', Validators.required],
email: ['', Validators.required],
role: ['', Validators.required],
password: ['', Validators.required],
password2: ['', Validators.required] },
{ validator: matchingPasswords('password', 'password2')
})
};
addUser() {
if (this.addForm.valid) {
var adduser = {
username: this.addForm.controls['username'].value,
email: this.addForm.controls['email'].value,
password: this.addForm.controls['password'].value,
profile: {
role: this.addForm.controls['role'].value,
name: this.addForm.controls['username'].value,
email: this.addForm.controls['email'].value
}
};
console.log(adduser);// adduser var contains all our form values. store it where you want
this.addForm.reset();// this will reset our form values to null
}
}
}
<div>
<form [formGroup]="addForm">
<input type="text" placeholder="Enter username" formControlName="username" />
<input type="text" placeholder="Enter Email Address" formControlName="email"/>
<input type="password" placeholder="Enter Password" formControlName="password" />
<input type="password" placeholder="Confirm Password" name="password2" formControlName="password2"/>
<div class='error' *ngIf="addForm.controls.password2.touched">
<div *ngIf="addForm.hasError('mismatchedPasswords')"> Passwords do not match
</div>
</div>
<select name="Role" formControlName="role">
<option value="admin" >Admin</option>
<option value="Accounts">Accounts</option>
<option value="guest">Guest</option>
</select>
<br/>
<br/>
<button type="submit" (click)="addUser()"> Add User </button>
</form>
</div>
export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
return (group: ControlGroup): {
[key: string]: any
} => {
let password = group.controls[passwordKey];
let confirmPassword = group.controls[confirmPasswordKey];
if (password.value !== confirmPassword.value) {
return {
mismatchedPasswords: true
};
}
}
}
答案 3 :(得分:0)
尝试了很多并从各种博客文章中获取帮助:我找到了解决方案
新组件文件
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
import { Checkpassword } from '../checkpassword';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
signUpForm: FormGroup;
constructor(fb: FormBuilder) {
this.signUpForm = fb.group({
oldpassword: ['', Validators.compose([
Validators.required,
Checkpassword.checkPasswordLength
])],
passwords: fb.group({
newpassword1: ['', Validators.required],
newpassword2: ['', Validators.required]
},{validator: Checkpassword.isSamePassword})
});
}
ngOnInit() {
}
onSubmit(){
console.dir(this.signUpForm.controls);
}
}
验证码文件:
import { FormControl, FormGroup } from '@angular/forms'
export class Checkpassword {
static checkPasswordLength(control: FormControl){
if(control.value.length > 0 && control.value.length < 5 ) return {smallPassword: true};
return null;
}
static isSamePassword(group: FormGroup){
let newpassword1 = group.controls['newpassword1'].value;
let newpassword2 = group.controls['newpassword2'].value;
if(newpassword1 !== newpassword2){
return {notSamePassword: true};
}
// console.dir(group.controls);
return null;
}
}
HTML文件
<div class="container">
<form [formGroup]="signUpForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="oldpassword">Old Password</label>
<input type="password"
name="oldpassword" formControlName="oldpassword"
class="form-control"
id="oldpassword">
</div>
<div *ngIf="signUpForm.controls.oldpassword.touched && !signUpForm.controls.oldpassword.valid">
<div class="alert alert-danger" *ngIf="signUpForm.controls.oldpassword.errors.smallPassword">
Old Password is too small
</div>
<div class="alert alert-danger" *ngIf="signUpForm.controls.oldpassword.errors.required">
Old Password is required
</div>
</div>
<div formGroupName="passwords">
<div class="form-group">
<label for="newpassword1">New Password</label>
<input type="password"
name="newpassword1" formControlName="newpassword1"
class="form-control"
id="newpassword1">
</div>
<div *ngIf="signUpForm.controls.passwords?.controls.newpassword1?.touched
&& !signUpForm.controls.passwords?.controls.newpassword1?.valid"
class="alert alert-danger">New Password is required</div>
<div class="form-group">
<label for="newpassword2">Confirm New Password</label>
<input type="password"
name="newpassword2" formControlName="newpassword2"
class="form-control"
id="newpassword2">
</div>
<div *ngIf="signUpForm.controls.passwords?.controls.newpassword2?.touched
&& !signUpForm.controls.passwords?.controls.newpassword2?.valid">
<div class="alert alert-danger">
Confirm password is required
</div>
</div>
<div class="alert alert-danger"
*ngIf="signUpForm.get('passwords').hasError('notSamePassword')">
Passwords do not match
</div>
</div>
<button class="btn btn-primary" type="submit">Change Password</button>
</form>
</div>