atl_andy Posted December 24, 2008 Share Posted December 24, 2008 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. example@example.com</p>'; var replace = document.getElementById('error'); replace.innerHTML = error; return false; } } } Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 24, 2008 Share Posted December 24, 2008 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. example@example.com</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 Quote Link to comment Share on other sites More sharing options...
atl_andy Posted December 25, 2008 Author Share Posted December 25, 2008 Thanks for the reply. I've gone to the one error way that you suggested. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.