If a validation script fails, how do I place focus back into the field until entered correctly

Joined
May 14, 2017
Messages
2
Reaction score
0
I want to make sure the user enters the correct information before moving on to another field. Here is an example:

<script type='text/javascript'>
function emailValidator(element, alertMsg){
var emailvalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(element.value.match(emailvalid))
{
return true;
}else{
alert(alertMsg);
return false;
}
}
</script>

The input in the form:

<h3><font color="#FF0000">*</font> Your E-Mail address: <input
type="text" size="30" name="email" value=" " id="email"
onblur="return emailValidator(document.getElementById('email'), 'This is not a valid Email');"></h3>

Like the codes is, it displays the error message but instead of going back to the email field, it goes on to the next
field input box.

Thanks for your help.
 
Joined
May 14, 2017
Messages
2
Reaction score
0
Figured it out:

<script type="text/javascript">
function emailValidator(element, alertMsg){
var emailvalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(element.value.match(emailvalid))
{
element.style.background = 'White';
return true;
}else{
element.style.background = 'Yellow';
alert(alertMsg);
myHidden.focus(); // place focus on dummy input because it has to go somewhere besides real one first
element.focus(); // place focus on real one
return false;
}
}
</script>

The input in the form:

<input type="hidden" id="myHidden" value=""/>

<h3><font color="#FF0000">*</font> Your E-Mail address: <input
type="text" size="30" name="email" value=" " id="email"
onblur="emailValidator(document.getElementById('email'), 'This is not a valid Email');"></h3>
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top