I am working on angular2 application in which I have to apply validation on the input fields.
I have same code here
http://plnkr.co/edit/6RkM0eRftf3KQpoDCktz?p=preview
Its work fine for me but i want to trigger the validation on button click and show the all the validation messages which are invalid
currently it activated when i click on fields.
I have tried this
saveUser() {
if (this.userForm.valid) {
alert(`Name: ${this.userForm.value.name} Email: ${this.userForm.value.email}`);
} else {
this.userForm.validator();
}
}
Its not working as expected.
How do i trigger those validation on button click, I want button to be active all the time.
You could try to leverage a submitted
property of the form control when displaying errors. This could be used in the corresponding ngIf
to display these messages.
<span *ngIf="submitted && !this.userForm.controls.email.valid">...</span>
You need to initialize the submitted
property to false by default and set it to true when calling the saveUser
method:
@Component({
})
export class SomeComponent {
constructor() {
this.submitted = false;
}
saveUser() {
this.submitted = true;
(...)
}
}
This way they will be visible only after the form has been submitted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.