我正在尝试创建一个Angular2 Reactive表单,我必须确认用户输入的电子邮件地址。以下是plunker
的链接import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { User } from './signup.interface';
@Component({
selector: 'signup-form',
template: `
<form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">
<label>
<span>Full name</span>
<input type="text" placeholder="Your full name" formControlName="name">
</label>
<div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('required')">
Name is required
</div>
<div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('minlength')">
Minimum of 2 characters
</div>
<div formGroupName="account">
<label>
<span>Email address</span>
<input type="email" placeholder="Your email address" formControlName="email">
</label>
<div
class="error"
*ngIf="user.get('account').get('email').hasError('required') && user.get('account').get('email').touched">
Email is required
</div>
<label>
<span>Confirm address</span>
<input type="email" placeholder="Confirm your email address" formControlName="confirm">
</label>
<div
class="error"
*ngIf="user.get('account').get('confirm').hasError('required') && user.get('account').get('confirm').touched">
Confirming email is required
</div>
</div>
<button type="submit" [disabled]="user.invalid">Sign up</button>
</form>
`
})
export class SignupFormComponent implements OnInit {
user: FormGroup;
constructor() {}
ngOnInit() {
this.user = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(2)]),
account: new FormGroup({
email: new FormControl('', Validators.required),
confirm: new FormControl('', Validators.required)
})
});
}
onSubmit({ value, valid }: { value: User, valid: boolean }) {
console.log(value, valid);
}
}
我想在这两个电子邮件字段不匹配时显示错误。
如何使用angular2?
中的反应形式为此行为创建此类验证我看到过一个使用模板驱动方法here执行此操作的帖子,但我无法弄清楚如何使用反应式表单方法来实现此目的。
答案 0 :(得分:10)
我使用反应形式完成了密码匹配。你可以改变电子邮件。只需更改电子邮件验证器代替密码即可。两者都是字符串其他一切都相同,并在电子邮件中输入密码匹配错误。它将工作
将这些添加到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') <-- replace args with email_1 and email_2
})
};
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 class="alert-danger errormessageadduser" *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()"><span><i class="fa fa-user-plus" aria-hidden="true"></i></span> 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
};
}
}
}