Reputation: 5834
I made a form using FormBuilder approach. Now I want to add some pattern validation.
I added the validation and it is working fine. But the validation error is showing at non desired time.
I have added one textfield
and added a pattern
validation. I wanted to show the error message when another control get selected or it looses focus.
But currently the validation error is showing as soon as I start entering text.
Can I show the error message in lost focus event. I know I can easily do it by binding a method in onChange
event of TextControl
but If there is another approach I will love to know that.
Upvotes: 1
Views: 907
Reputation: 7242
yes you can do it subscribe valuechange on particular one control valuechanges.
for Example **
first method
import...
@Component({..})
export class ExampleComponent implements OnInit {
ngOnInit(): void {
this.formName.get('name')
.valueChanges
.filter((value: string) => value != null && value.length > 0) // use filter if needed otherwise remove it
.subscribe((value: string) => {
if (!value.match(/[-!$%^&*(/]/... set here your pettern)) {
this.formName.controls.name.setErrors({});
}
}
}
}
second method
html
<input type='text' (blur)="checkValidation()" formControlName="name">
{{errorMessage}}
Method in component
import...
@Component({..})
export class ExampleComponent implements OnInit {
errorMessage ='';
ngOnInit(): void {
}
checkValidation(): void {
if (!value.match(/[-!$%^&*(/]/... set here your pettern)) {
this.formName.controls.name.setErrors({});
this.errorMessage = 'set here your message';
}
}
Upvotes: 1