Jump to content

[SOLVED] onblur event handler


atl_andy

Recommended Posts

Which is better to use for validation on the client, onblur or onchange?  onblur does some wierd stuff if you tab off a field and tab back through.  It will throw an error even though the value is valid.  It's like it sends a blank value on the second tab.  I have changed to onchange to avoid this issue, but wanted to get some opinions on which is the preferred method.  ie, real world experience.

 

<input type="text" id="email" name="email" size="25" maxlength="50" onblur="validateEmail();"/>

 

function validateEmail()
{
var email = document.getElementById('email').value;

if (email.length == 0) {
	var error ='<p class="error">Please enter your email address.</p>';
	var replace = document.getElementById('error');
	replace.innerHTML = error;
	return false;
}
if (email.length > 0) {
	var checkEmail = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/mgi.test( email );

	if (checkEmail == false) {
		var error = '<p class="error">Please enter a valid email address.<br />eg. [email protected]</p>';
		var replace = document.getElementById('error');
		replace.innerHTML = error;
		return false;
	}
}
}

Link to comment
https://forums.phpfreaks.com/topic/138266-solved-onblur-event-handler/
Share on other sites

Well, I would do either onchange of the field or onsubmit of the form (or both). But I would change your logic a little.

 

For one I would only check for an empty input onsubmit of the form. A user should be able to enter and exit a field on a form (even a required field) without getting an error. Only check for required field on submission of the form.

 

function validateSubmission()
{
    //Other validations

    emailObj = document.getElementById('email');
    if (!emailObj.value)
    {
        //Present the error
        emailObj.focus();
        return false;
    }
    else if (!validEmail(emailObj))
    {
        //Present the error
        emailObj.focus();
        return false;
    }

    //Other validations
}

function validEmail(emailObj)
{
    var isEmail = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/mgi;
    if (!isEmail.test(emailObj.value))
    {
        var error = '<p class="error">Please enter a valid email address.<br />eg. [email protected]</p>';
        document.getElementById('error').innerHTML = error;
        return false;
    }
}

 

Actually for the submission validation I would test for all errors then display a single error with all of the problems, this was just a samle script

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.