0

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

Mr.X
  • 117
  • 8
  • `on*` attributes should be changed to their parentheses variant (for e.g. `onfocusout` should be `(focusout)`). – Edric Oct 27 '20 at 07:51

2 Answers2

2

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" }],
});
Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

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">
Julien
  • 2,256
  • 3
  • 26
  • 31
  • you are using formControl and pattern and input !!!, If you are using ReactiveForms, the validators should been created when create the FormControl – Eliseo Oct 27 '20 at 09:19