/    Sign up×
Community /Pin to ProfileBookmark

form submits before validation

Hi —

I have a form with some javascript validation code for phone # and email address. If the user completes the form without making a mistake, the form submits normally. But if the user doesn’t initially include a valid email address (for example) and receives the error message, instead of waiting for the user to complete the form correctly, the form submits prematurely.

If anyone can spot what’s wrong, I’d very much appreciate any feedback.

Here is my code:

[CODE]

<script language=”javascript” type=”text/javascript”>
function validate_onclick()
{

var textbox3 = document.getElementById(“phone”);
var myregex = /d{3}-d{3}-d{4}/g;
if (textbox3.value == “”) {
alert(“You did not enter your phone number in the textbox. Please enter before submitting form. n”);
textbox3.focus();
return false;
}
else if (!textbox3.value.match(myregex)) {
alert(“Please enter a valid phone number.”);
textbox3.focus();
return false;
}

var textbox4 = document.getElementById(“email”);
var regex2 = /^w+-?w*@w+-?w*.(w+$)/gi;
if (textbox4.value == “”) {
alert(“You did not enter your email address in the textbox. Please enter before submitting form. n”);
textbox4.focus();
return false;
}
else if (!textbox4.value.match(regex2)) {
alert(“Please enter a valid email address.”);
textbox4.focus();
return false;
}

}

</script>

<label for=”phone”>Phone (###-###-####)</label><br>
<input type=”text” name=”phone” id=”phone” size=”50″ maxlength=”50″ tabindex=”3″>
<br /><br />

<label for=”email”>Email</label><br>
<input type=”text” name=”email” id=”email” size=”50″ maxlength=”50″ tabindex=”4″>
<br /><br />

<input type=”submit” name=”Form_Submit” value=”Submit Form” onClick=”validate_onclick();”>

[/CODE]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@gil_davisApr 11.2007 — You need to put the validation in the FORM onsubmit event. Using onclick of the "submit" button will not prevent submission.&lt;form ... onsubmit="return validate_onclick()"&gt;
Copy linkTweet thisAlerts:
@baronauthorApr 12.2007 — Thank you so much!
×

Success!

Help @baron spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...