Validating input field when it losses focus
Tags: webdev, javascript, beginners, html
Published: 2022-08-14 12:41:13

There are going to be several scenarios where you will have to call a function when the input field is set to inactive. May be you want to call an api or you want to validate a form field as soon as the input field is out of focus.

### onblur

onblur function fires the moment input field is out of focus. This event is not cancelable and does not [bubble](https://www.geeksforgeeks.org/event-bubbling-in-javascript/). 

opposite of onblur is [**onfocus**](https://developer.mozilla.org/en-US/docs/Web/API/Element/focus_event).

### Let code to understand this better

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Validation of field on focs out</title>
</head>
<body>
    <form method="post"  >
        <input type="text" placeholder="Email" id='email'>
        <span id='email-error'></span>
        <input type="password" placeholder="Password" id='password' >
        <span id='password-error'></span>
    </form>
</body>
<script>
    const email =document.getElementById("email")
    const pasword =document.getElementById("password")

    pasword.addEventListener('blur',()=>{
        const error= document.getElementById('password-error')
        if(pasword.value?.length < 8){
            error.innerHTML = "password must be 8 or more characters"
            returnb
        }
        error.innerHTML = ""
        
    })
    email.addEventListener('blur',()=>{
        const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        const error= document.getElementById('email-error')
        if(email.value.match(emailRegex)) {
            error.innerHTML = ""
            return
        }
        error.innerHTML = "invalid email"
    })
</script>
</html>
```

### Code explaination

we are validation both the password field and email field when they are set to inactive.

In **script**  tag we have attached blur event to both the field which mean as soon as the field go out of focus the second parameter of the **addEventListner**  which is a function will be triggered.

#### Email validation

We are use regex to validate our email field. We are checking if the value of email field satisfies the regex if it does then we will remove the error from the error **span** and if the regex is not satisfied we will populate an error saying **invalid email**

#### Password validation

For password validation we are check if the length of password is greater then or equal to 8 if it is then we will empty the error **span** of password and if it is not then we will display error saying **password must be 8 or more characters**.

### Conclusion

You will face a lot of scenarios in your development career where you will have to validate a field or call a function when the field is set to inactive. I have tried to give you a some basic understanding of how you can achieve that . 

If you have any queries or suggestions leave them in comment. 

Thanks