SitePoint Sponsor

User Tag List

Results 1 to 6 of 6

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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>
    If you click the submit button, you get error messages on Email and URL fields while they are optional. How can I prevent it?

  2. #2
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Posts
    41
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    the jQuery Validation plugin you are using has a set of default classes it checks. Your e-mail and url input fields each have one of those default classes, namely "email" and "url".

    The plugin doesn't check if they are required, because they aren't (you didn't add the class "required" to them), but it does check if the value (the default values ,"Email" and "URL") entered is an e-mailaddress and if the other is a valid url.

    To solve your problem, you should place an "onsubmit" on your form, which removes the default values from the e-mail and url input fields.

    +

    You're creating a new method for "name" and "comment", which is bad practice... You shouldn't create new methodes for the thing you're trying to achieve... As said a few lines above, you should place an onsubmit on the form which removes the default values of all your fields. If however an error should occur, then the default value would be removed from these fields. You can overcome that by storing the default values in an array on page load, for example (there are a lot of other options).

    I see that you aren't using HTML5, if you were, you could have used the "placeholder"-attribute. EVenthough not every browser supports it, you could recreate the same type of behaviour.

    I believe I've given you enough information in regards to the problem you're having. If you run into any more issues, feel free to post them here.

  3. #3
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the answer!

    Quote Originally Posted by Denk View Post
    You can overcome that by storing the default values in an array on page load, for example (there are a lot of other options).
    I don't know how to do it. A sample code might help me understand it better.

  4. #4
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Posts
    41
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Here is an example! There might be easier ways to accomplish this behaviour, but this is the first idea that came to mind.

    Code JavaScript:
    // get the elements and store their values in an array
    var elements = $( "input:not(.submit), textarea" );
    var formSerializeArray = elements.serializeArray(); // store defaultValues
    var defaultValues = [];
    $(formSerializeArray).each(function(index, value){
    	defaultValues[value.name] = value.value;						
    });
     
    // your code
    $("#cname, #cemail, #curl, #ccomment").focus(function(){
    	if( this.value == this.defaultValue ) {
    		$(this).val("");
    	}
    }).blur(function() {
    	if( !this.value.length ) {
    		$(this).val(this.defaultValue);
    	}
    });
     
    // remove the default values
    $("#commentForm").submit(function(){
    	elements.each(function(){
    		if( $.inArray($(this).val(), defaultValues ) && $.inArray($(this).attr("name"), defaultValues )){
    			$(this).val("");
    		}
    	});
    });
     
    // validate and restore the defaultValues if an error occured
    $("#commentForm").validate({
    	"invalidHandler": function(){
    		for(var elm in defaultValues){
    			elements.filter("[name='" + elm + "']").val(defaultValues[elm]);
    		}
    	}
    });

  5. #5
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Denk View Post
    Here is an example! There might be easier ways to accomplish this behaviour, but this is the first idea that came to mind....
    Doesn't work right, but it might give me some ideas. Thanks anyway!

  6. #6
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Posts
    41
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Works fine for me... what doesn't work?

    ok, good luck :-)


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •