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

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:

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

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:


$.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:


<input id="cname" name="name" value="Name" class="required noPlaceholder" ... />

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.

<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
            }
        }
});
});

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.

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?

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.

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.

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?

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

/* 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?


You’re the JavaScript guru! Thanks! :slight_smile:
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?


$.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.


<input name="url" class="removePlaceholder url" value="URL" ... />

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.

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.

Dear Paul,

You’re an angel! Thank you so much!

Thanks from me too Paul!

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

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!