Validate form field after user leaves the field

1.6k Views Asked by At

I want to validate a form field after user has left the field. I wrote my html as below

 <input type="text" onfocusout="validateIp()"formControlName="ip_address" (input)="onIpChange($event.target.value)" pattern="^[a-zA-Z0-9.]*$"class="form-control form-control-sm" id="IP_Address">

Below is my typescript code

 validateIp(){
    
    console.log('validateIp is called');
  }

onfocusout is not working as expected . Below is error I am getting

Uncaught ReferenceError: validateIp is not defined
    at HTMLInputElement.onfocusout 

I have tried onblur also but event is not getting triggered

2

There are 2 best solutions below

1
Julien On

It seems that you are inside an Angular component and that you are trying to call a method of this component.

Given that onIpChange is defined in the same component as validateIp, you have to change your HTML code from

<input type="text" onfocusout="validateIp()" formControlName="ip_address" (input)="onIpChange($event.target.value)" pattern="^[a-zA-Z0-9.]*$"class="form-control form-control-sm" id="IP_Address">

to

<input type="text" (focusout)="validateIp()" formControlName="ip_address" (input)="onIpChange($event.target.value)" pattern="^[a-zA-Z0-9.]*$" class="form-control form-control-sm" id="IP_Address">
0
Eliseo On

when use ReactiveForms, you can validate onBlur

this.form=new FormGroup({
  ip_address:new FormControl(null,{validators: Validators.required,
                                  updateOn: 'blur'})
})

Or using formBuilder

this.form = this.fb.group({
    ip_address: ["", { validators: [Validators.required], updateOn: "blur" }],
});