you can easy archive this by using Reactive Forms and Validator in Angular, here is simple example of register component with validate same password.
note: you could learn more about Reactive Forms in this document https://angular.io/docs/ts/latest/guide/reactive-forms.html
First, we need import Reactive Forms Module to our app:
@NgModule({
imports: [ BrowserModule, ReactiveFormsModule ], // <- this module
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
and create new Component:
@Component({
selector: 'tpc-register',
template: `
<form [formGroup]="form" novalidate (ngSubmit)="onSubmit()">
<div>
<label>
Username:<br>
<input formControlName="username" type="text">
</label>
</div>
<div formGroupName="passGroup">
<label>
Password:<br>
<input formControlName="password" type="password"
[class.form-error]="form.get('passGroup').errors?.invalid"
>
</label>
</div>
<div formGroupName="passGroup">
<label>
Confirm Password:<br>
<input formControlName="confirmPassword" type="password"
[class.form-error]="form.get('passGroup').errors?.invalid"
>
</label>
</div>
<button [disabled]="form.invalid">Register</button>
</form>
<pre>Form value: {{ form.value | json }}</pre>
<pre>Form valid: {{ form.valid }}</pre>
`,
styles: [
`
.form-error {
border-color: red
}
`
]
})
export class TpcRegister implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
// create new Form by FormBuilder
this.form = this.fb.group({
username: ['', /* Validation */[Validators.required]],
// for password and confirm password
passGroup: this.fb.group({
password: ['', /* Validation */[Validators.required]],
confirmPassword: ['', /* Validation */[Validators.required]],
}, /* Custom Validation */ {
validator: comparePassword
})
})
}
onSubmit() {
if (this.form.valid) {
const formValue = Object.assign({}, this.form.value)
formValue.password = formValue.passGroup.password
delete formValue.passGroup
// do stuff to register user with formValue
console.log(formValue)
}
}
}
please take a look to ngOnInit
method, the magic stuff happen here.
We create passGroup
and apply custom validator for this group, in this case is comparePassword
.
export function comparePassword(group: FormGroup) {
const pass = group.value;
return (pass.password === pass.confirmPassword) ? null /* It's good */ : {
invalid: true
}
}
the above function will take a group
of type FormGroup
, then we could compare values of password
and confirmPassword
.
if they are same, so nothing error here, we return null, otherwise we will return an object to tell our app this group has errors.
You can play with live demo here: https://plnkr.co/edit/Vk0G7DaPB1hRK9f1UVEX?p=preview