/    Sign up×
Community /Pin to ProfileBookmark

Can JavaScript stop a form from being submitted?

I was wondering if there was a way to keep a form from being submitted with erroneous information.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@FangNov 20.2010 — With a validation script you can, but checks MUST be made server-side as well.
Copy linkTweet thisAlerts:
@Mr_Initial_ManauthorNov 20.2010 — Validation script?
Copy linkTweet thisAlerts:
@FangNov 20.2010 — Basic construct[CODE]<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>

<script type="text/javascript">
window.onload=function() {
document.forms[0].onsubmit = function() {return validate(this);};
};

function validate(f) {
if(f.foobar.value==='') {
alert('foobar is empty');
f.foobar.focus();
return false;
}
return true;
}
</script>

<style type="text/css">
* {margin:0;padding:0;}
</style>

</head>
<body>
<form action="" method="post" name="form1">
<label>foobar: <input type="text" name="foobar"></label>
<button type="submit">submit</button>
</form>
</body>
</html>
[/CODE]
×

Success!

Help @Mr_Initial_Man 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.18,
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,
)...