/    Sign up×
Community /Pin to ProfileBookmark

JavaScript Form Validation

Hi there

Im new to the forum and wondering if someone could point me in the right directtion.

I have a html web form and Im trying to use JavaScript to validate the form before submitting.

Here’s my code so far:

function validate_form ( )
{

if (document.frm_contact_us.txtname.value == “”)
{
alert(“Please fill in the ‘Your Name’ box.”);
document.frm_contact_us.txtname.focus()
return false;
}
return true;

}

The problem is that even though javascript bring up an Alert box to notify that the txtname field is blank, the Form still get submitted – and I cant figure out why.

Any Pointers with would be greatly appreciated.

Thanks, James

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@aj_nscSep 22.2009 — Your function is fine, but it needs to return either true or false to the form onsubmit, as below:

[code=html]
<form name="frm_contact_us" method="whatever" onsubmit="return validate_form()">
...your form here
</form>
[/code]
Copy linkTweet thisAlerts:
@jamez100authorSep 22.2009 — aj_nsc - You are legend.

Ta very much

Worked a treat

Rgds, James
×

Success!

Help @jamez100 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 6.17,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...