Unbreakable Unbreakable - 8 months ago 27
Javascript Question

How to validate a field as soon as it loses focus

I am learning web development. And I have a login form where I have two text field one for email and one for password. I want to have validation for email field. Currently, I am able to validate but it occurs when I click on submit button. Is there an way I can do the validation as soon as the email field loses focus. I want to call

method as soon as focus loses.

This is what I have till now:


<div id="ErrMsg" style="color:red">
<form id="myForm" action = "" method="post">
<input id="email" name="Email" type="email" class="form-control" placeholder="Email">
<input id="pass" name="Password" type="password" class="form-control" placeholder="Password" />
<button id="signIn" type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>

JS File

window.loginView = Backbone.View.extend({
events: {
'click #signIn': 'doSignIn',
initialize: function() {
console.log('Initializing Login View');
validateEmail: function(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
doSignIn: function(event) {
var email = $("#email").val();
// checking if email is valid
if (!this.validateEmail(email)) {
$("#ErrMsg").text(email + " is not valid :(");
// some logic to fetch data from REST


Yes, there is a way. You can bind an focusout event.

EDIT: add another event (after 'click #signIn': 'doSignIn'):

'focusout #signIn': 'doSignIn'