开发者

How do you validate optional fields with default value?

I made some changes to the following example:

http://docs.jquery.com/Plugins/validation#Example

<!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; }
</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="35" rows="5" 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>

I know how to add custom validation methods for the required fields Name, Email, and Comment. But I just don't know how to validate the optional filed URL. I've 开发者_如何转开发searched everywhere to no avail!

Any help is greatly appreciated!

Desparate


You can look at the code of url2 method from the additional-methods.js and create your own method based on the code. Inside the your custom validation method you can compare the current url value with your default "URL" string and interpret the text as the empty string or something other depends on your requirements.

UPDATED: I looked one more time in your code and found out that the real problem which you has is that you place hint texts inside of the form fields. It follows that the validate plugin try to validate the hints. For example you place "Name" in the name field of the form. The field you mark as required, but in your original code the validate plugin get the "Name" text as the input and all looks valid.

So it seems to me that you can really solve the problem if you will cut the default values from the input fields before validation. I have not found and direct way to do this, so I overwrite two functions of the validate plugin: clean and focusInvalid. Moreover I replaced usage of 'onfocus' and 'onblur' to there unobtrusive version.

At the end, after small bug fixing in the HTML, the code will be following

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>How do you validate optional fields with default value</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/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; }
  </style>
  <script type="text/javascript">
  $(document).ready(function(){
    var defaultValues = {
          // the property name is the value of the "name" attribute in the form
          name: "Name",
          email: "Email",
          url: "URL",
          comment: "Comment"
        },
        form = $("#commentForm"),
        resetDefaults = function() {
          var n, el;
          for (n in defaultValues) {
            if (defaultValues.hasOwnProperty(n)) {
              el = $("input[name='"+n+"'], textarea[name='"+n+"']",form[0]);
              if (el.length === 1 && el[0].value === "") {
                el[0].value = defaultValues[n];
              }
            }
          }
        };

    resetDefaults(); // fill form defaults
    $("input[name], textarea[name]",form[0])
      .focusin(function() {
          if (defaultValues.hasOwnProperty(this.name) && this.value === defaultValues[this.name]) {
            this.value = '';
          }
      })
      .focusout(function() {
          if (defaultValues.hasOwnProperty(this.name) && this.value === '') {
            this.value = defaultValues[this.name];
          }
      });
    form.validate();

    // now we subclass "clean" and "focusInvalid" methods of the validator
    form.data('validator').clean = function(elem) {
      if (elem) {
        if (defaultValues.hasOwnProperty(elem.name) && elem.value === defaultValues[elem.name]) {
            elem.value = '';
        }
      }
      return $(elem)[0];
    };
    var oldFocusInvalid = $("#commentForm").data('validator').focusInvalid;
    $("#commentForm").data('validator').focusInvalid = function( selector ) {
        oldFocusInvalid.call(this); // call the original method
        resetDefaults();
    };
  });
  </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">
   </p>
   <p>
     <input id="cemail" name="email" size="25"  class="required email">
   </p>
   <p>
     <input id="curl" name="url" size="25"  class="url">
   </p>
   <p>
     <textarea id="ccomment" name="comment" cols="35" rows="5" class="required"></textarea>
   </p>
   <p>
     <input class="submit" type="submit" value="Submit">
   </p>
 </fieldset>
 </form>
</body>
</html>

You can see the demo live here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜