如何使用默认值验证可选字段?

时间:2011-02-27 11:59:24

标签: jquery jquery-validate

我对以下示例进行了一些更改:

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>

我知道如何为必填字段Name,Email和Comment添加自定义验证方法。但我只是不知道如何验证可选的归档URL。我到处搜索都无济于事!

非常感谢任何帮助!

绝望

1 个答案:

答案 0 :(得分:1)

您可以从additional-methods.js查看url2方法的代码,并根据代码创建自己的方法。在自定义验证方法中,您可以将当前url值与默认的“URL”字符串进行比较,并将文本解释为空字符串或其他内容取决于您的要求。

更新:我再次查看代码,发现您遇到的真正问题是将提示文本放在表单字段中。因此,验证插件尝试验证提示。例如,您将“名称”放在表单的名称字段中。您根据需要标记的字段,但在原始代码中,验证插件将“名称”文本作为输入,并且所有内容看起来都有效。

所以在我看来,如果你在验证之前从输入字段中删除默认值,你就可以真正解决问题。我没有找到并直接执行此操作,因此我覆盖了validate插件的两个函数:cleanfocusInvalid。此外,我将“onfocus”和“onblur”的使用替换为unobtrusive版本。

最后,在HTML中修复小错误之后,代码将会跟随

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

您可以直接观看演示here