SitePoint Sponsor

User Tag List

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

    How to ignore default text in jQuery validation?

    Hi,

    I'd like to use the jQuery validation plugin as seen on the following example:
    http://docs.jquery.com/Plugins/validation#Example

    But it doesn't work properly if I use inline/in-filed labels.


    Any help is appreciated!
    Rain Lover

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    I'd like to use the jQuery validation plugin as seen on the following example:
    http://docs.jquery.com/Plugins/validation#Example

    But it doesn't work properly if I use inline/in-filed labels.
    Please post the HTML code that is not working as expected, or better yet, link us to a test page that demonstrates the problem.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Please post the HTML code that is not working as expected, or better yet, link us to a test page that demonstrates the problem.
    Thanks for the answer! I just removed labels and added default values instead. I also added some onFocus/onBlur events:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                        "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
      <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
    <style type="text/css">
    * { font-family: Verdana; font-size: 96%; }
    label { width: 10em; float: left; }
    label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
    p { clear: both; }
    .submit { margin-left: 12em; }
    em { font-weight: bold; padding-right: 1em; vertical-align: top; }
    </style>
      <script>
      $(document).ready(function(){
        $("#commentForm").validate();
      });
      </script>
      
    </head>
    <body>
      
    
     <form class="cmxform" id="commentForm" method="get" action="">
     <fieldset>
       <legend>A simple comment form with submit validation and default messages</legend>
       <p>
         <input id="cname" name="name" size="25" class="required" value="Name" onfocus="if (this.value == 'Name') {this.value=''}" onblur="if(this.value == '') { this.value='Name'}" />
       </p>
       <p>
         <input id="cemail" name="email" size="25"  class="required email" value="Email" onfocus="if (this.value == 'Email') {this.value=''}" onblur="if(this.value == '') { this.value='Email'}" />
       </p>
       <p>
         <input id="curl" name="url" size="25"  class="url" value="URL" onfocus="if (this.value == 'URL') {this.value=''}" onblur="if(this.value == '') { this.value='URL'}" />
       </p>
       <p>
         <textarea id="ccomment" name="comment" cols="22"  class="required" onfocus="if (this.value == 'Comment') {this.value=''}" onblur="if(this.value == '') { this.value='Comment'}">Comment</textarea>
       </p>
       <p>
         <input class="submit" type="submit" value="Submit"/>
       </p>
     </fieldset>
     </form>
    </body>
    </html>

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Where you already have default values, the required class automatically considers those to be values, so you need to add another validation class which doesn't allow default values.

    What you can do is to add a new validation method called noPlaceholder:

    Code javascript:
    $.validator.addMethod(
        'noPlaceholder', function (value, element) {
            return value !== element.defaultValue;
        }, 'Please enter a value.'
    );

    and refer to the noPlaceholder rule from each appropriate form element:

    Code html4strict:
    <input id="cname" name="name" value="Name" class="required noPlaceholder" ... />
    Last edited by paul_wilkins; Feb 20, 2011 at 06:32.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Member
    Join Date
    Feb 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've run into a similar promlem placing hints as default values.

    The additional method provided above stops default values passing the required rule, but some hints still cause validation erros against other rules.

    Can anyone provide advice on creating an additional method which only triggers validation if the default value has changed.

    For example, I require people to enter an 11 digit number. I have "no spaces" as the default value.

    If I apply the noPlaceholder method from above, and the digits method jQuery Validate offers, my default value doesn't pass the digits method.


    Code:
    <form id="form">
    <label for="abn">ABN</label>
    <input type="text" id="complaintabn" name="ABN" value="no spaces" class="hint">
    </form>
    
    <script>
    $(document.ready(function(){
    $('#form').validate({
        rules: {
            ABN: {
                noPlaceholder: true,
                digits: true
                }
            }
    });
    });

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by AndrewJFleming View Post
    If I apply the noPlaceholder method from above, and the digits method jQuery Validate offers, my default value doesn't pass the digits method.
    The noPlaceholder validation should only be used when you do not want the default value to be allowed for validation.

    If you do want the default value to be allowed, then just do not specify the noPlaceholder rule for that form input.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Member
    Join Date
    Feb 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply Paul.

    I want the validation rules to run only if the default value has been changed. If the example form from above is submitted it does not pass the digits method.

    Can you give me advice on creating an additional method which checks if the default value has been changed, and only validates if it has changed.

    Is an additional method the best way to solve this?

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by AndrewJFleming View Post
    I want the validation rules to run only if the default value has been changed. If the example form from above is submitted it does not pass the digits method.
    So you want the validations to be performed in a special order. First the noPlaceholder ones, and only when they successfully pass, the other validations for those inputs.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Member
    Join Date
    Feb 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Not quite.

    I only want the validations to occure if the default value has been changed.

    Referring to the example above, the "no spaces" hint should not trigger any validation until the user has changed the value to something else. If a user enters something, then I need to apply validation.

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by AndrewJFleming View Post
    Referring to the example above, the "no spaces" hint should not trigger any validation until the user has changed the value to something else.
    If no validation occurs on it, there will be submitted "no spaces" for that field if it hasn't changed. Do you consider that to be acceptable?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  11. #11
    SitePoint Member
    Join Date
    Feb 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, that would not be acceptable.

    I'm thinking now a solution might include the jQuery I'm using to show and hide the hints when the inputs revieve focus

    Code JavaScript:
    /* Remove hints from inputs
    	*/
    	  $('.hint').each(function() {
        $(this)
          .data('default', $(this).val())
          .addClass('inactive')
          .focus(function() {
            $(this).removeClass('inactive');
            if($(this).val() == $(this).data('default') || '') {
              $(this).val('');
            }
          })
          .blur(function() {
            var default_val = $(this).data('default');
            if($(this).val() == '') {
              $(this).addClass('inactive');
              $(this).val($(this).data('default'));
            }
          });
      });

    Would adding a .submit section to this code which replicates the .focus functionality (clearing the default value) be a step toward providing hints which do not interfear with validation and do not submit?
    Code JavaScript:
     
    Last edited by AndrewJFleming; Feb 20, 2011 at 22:26. Reason: Correcting the code highlighting

  12. #12
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Where you already have default values, the required class automatically considers those to be values, so you need to add another validation class which doesn't allow default values.

    What you can do is to add a new validation method called noPlaceholder...
    You're the JavaScript guru! Thanks!
    It seems perfect for required/mandatory fields? How about for URL, which is optional?

  13. #13
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    You're the JavaScript guru! Thanks!
    It seems perfect for required/mandatory fields? How about for URL, which is optional?
    First, what is the expected behaviour when the default URL has not changed? That the default value be changed to an empty string?

    Code javascript:
    $.validator.addMethod(
        'removePlaceholder', function (value, element) {
            if (element.value === element.defaultValue) {
                element.value = '';
            }
            return true;
        }, ''
    );

    With that method, we should be able to specify what we need on the field.

    Code html4strict:
    <input name="url" class="removePlaceholder url" value="URL" ... />
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  14. #14
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    With that method, we should be able to specify what we need on the field.
    I'm almost done! But I don't like the URL field to be empty after submission. Ideally I wish to keep the word "URL" but don't submit it to the server after a successful submission.

  15. #15
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    I'm almost done! But I don't like the URL field to be empty after submission. Ideally I wish to keep the word "URL" but don't submit it to the server after a successful submission.
    I think that those two wishes might be incompatible with each other.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  16. #16
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry to bother you, but can we remove it temporarily on submission and then get it back?

  17. #17
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    Sorry to bother you, but can we remove it temporarily on submission and then get it back?
    Submission is when the current page is unloaded, and replaced with the next page, so any and all scripting also stops.

    If the empty field were to be replaced, it would have to be with scripting as the page loads. But consider this - when scripting adds that name to the previously empty field, the default value of the field is still an empty string, whereas before it was the field value. The newly added value will be considered false by the validation should it be submitted again.

    One possible solution is to submit to a server-side page, such as PHP, which fills in empty fields with a default value. That would work.
    I'm not aware of any other clean way to resolve that issue, and I don't do ugly without vast wads of cash.

    So other than that, we may have to wait for someone else who might have a more workable solution for you.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  18. #18
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Dear Paul,

    You're an angel! Thank you so much!

  19. #19
    SitePoint Member
    Join Date
    Feb 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks from me too Paul!

    The removePlaceholder method was what I was after! Thanks again.

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

    I spent three whole days studying jQuery references and documents to figure the following problem out and not to bother you again to no avail!
    After a successful submit the optional field "URL" gets empty and that's no problem. But before a successful submission if the user hits the submit button, the URL field hint/defaltvalue gets removed and it's against the form usability. I'd like the default value to be removed only after a successful submission.
    It's something easy for you that takes me months to work out. Please help me again!

    God bless you and your loved ones!

  21. #21
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Rain Lover View Post
    But before a successful submission if the user hits the submit button, the URL field hint/defaltvalue gets removed and it's against the form usability. I'd like the default value to be removed only after a successful submission.
    If you want the field values to remain, those field values will be submitted with the form.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  22. #22
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    If you want the field values to remain, those field values will be submitted with the form.
    OK. Here's my attempts result:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                        "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
      <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
    <style type="text/css">
    * { font-family: Verdana; font-size: 96%; }
    label { width: 10em; float: left; }
    label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
    p { clear: both; }
    .submit { margin-left: 12em; }
    em { font-weight: bold; padding-right: 1em; vertical-align: top; }
    </style>
      <script>
      $(document).ready(function(){
    $.validator.addMethod(
        'noName', function (value, element) {
            return value !== element.defaultValue;
        }, 'Please enter your name.'
    );
    $.validator.addMethod(
        'noEmail', function (value, element) {
            return value !== element.defaultValue;
        }, 'Please enter your Email.'
    );$.validator.addMethod(
        'noComment', function (value, element) {
            return value !== element.defaultValue;
        }, 'Please enter your comment.'
    );
        $("form").validate({
       success: "valid",
       submitHandler: function() { 
        if ($("#curl").val() == "URL")  
          $("#curl").val("");
          form.submit(); 
      } 
    })   
      }); 
      </script>  
      
    </head>
    <body> 
      
    
     <form class="cmxform" id="commentForm" method="get" action="">
     <fieldset>
       <legend>A simple comment form with submit validation and default messages</legend>
       <p>
         <input id="cname" name="name" size="25" class="required noName" value="Name" onfocus="if (this.value == 'Name') {this.value=''}" onblur="if(this.value == '') { this.value='Name'}" />
       </p>
       <p>
         <input id="cemail" name="email" size="25"  class="required noEmail email" value="Email" onfocus="if (this.value == 'Email') {this.value=''}" onblur="if(this.value == '') { this.value='Email'}" />
       </p>
       <p>
         <input id="curl" name="url" size="25"  class="" value="URL" onfocus="if (this.value == 'URL') {this.value=''}" onblur="if(this.value == '') { this.value='URL'}" />
       </p>
       <p>
         <textarea id="ccomment" name="comment" cols="22"  class="required noComment" onfocus="if (this.value == 'Comment') {this.value=''}" onblur="if(this.value == '') { this.value='Comment'}">Comment</textarea>
       </p>
       <p>
         <input class="submit" type="submit" value="Submit"/>
       </p>
     </fieldset>
     </form>
    <script>
        $("form").submit(function() {
          if ($("#curl").val() != "URL") {
            $("#curl").addClass("url");
          }
    else {$("#curl").removeClass("url");}
        });
    </script>
    </body>
    </html>

    How do you evaluate it? Is the coding correct?

  23. #23
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    222
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The idea I tried to implement are:
    1. Validate the filed only if the user enters something
    2. Remove the word "URL" on a successful submission


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
  •