/    Sign up×
Community /Pin to ProfileBookmark

Validate optional form fields with default values

Sample form:

[CODE]<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title></title>
<script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js”></script>
<script type=”text/javascript” src=”http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){
$(“#cname, #cemail, #curl, #ccomment”).focus(function(){
if( this.value == this.defaultValue ) {
$(this).val(“”);
}
}).blur(function() {
if( !this.value.length ) {
$(this).val(this.defaultValue);
}
});
$.validator.addMethod(“noName”, function(value, element) {
return value != element.defaultValue;
}, “Please enter your name.”);
$.validator.addMethod(“noComment”, function(value, element) {
return value != element.defaultValue;
}, “Please enter your comment.”);
$(“#commentForm”).validate();
});
</script>
</head>
<body>
<form id=”commentForm” action=””>
<p>
<input id=”cname” name=”name” size=”25″ class=”required noName” value=”Name”>
</p>
<p>
<input id=”cemail” name=”email” size=”25″ class=”email” value=”Email”>
</p>
<p>
<input id=”curl” name=”url” size=”25″ class=”url” value=”URL”>
</p>
<p>
<textarea id=”ccomment” name=”comment” rows=”5″ cols=”35″ class=”required noComment”>Comment</textarea>
</p>
<p>
<input class=”submit” type=”submit” value=”Submit”>
</p>
</form>
</body>
</html>[/CODE]

If you click the submit button, you get error messages on [I]Email[/I] and [I]URL[/I] fields while they are optional. How can I prevent it?

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @Rain_Lover 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 7.21,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ,
analytics: Fullres
});

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: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,

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