Jump to content

Validate optional form fields with default values


Rain Lover

Recommended Posts

Sample form:

<!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>

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

Link to comment
Share on other sites

did you look in the documentation?http://docs.jquery.com/Plugins/Validationhttp://docs.jquery.com/Plugins/Validation/Methods/required

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...