如何验证具有默认值的可选字段? [英] How do you validate optional fields with default value?

查看:49
本文介绍了如何验证具有默认值的可选字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

我知道如何为必填字段名称",电子邮件"和注释"添加自定义验证方法.但是我只是不知道如何验证可选的归档URL.我到处搜索都无济于事!

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!

任何帮助将不胜感激!

绝望

推荐答案

您可以从

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.

更新:我又看了一次您的代码,发现真正的问题是将提示文本放在表单字段中.因此,validate插件将尝试验证提示.例如,您将名称"放置在表单的名称字段中.您将该字段标记为必填字段,但是在原始代码中,validate插件将输入名称"文本作为输入,并且所有字段均有效.

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.

在我看来,如果您在验证之前 从输入字段中删除默认值,则可以真正解决问题.我尚未找到执行此操作的直接方法,因此我覆盖了validate插件的两个功能:cleanfocusInvalid.此外,我在不引人注目的版本中替换了"onfocus"和"onblur"的用法.

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.

最后,修复HTML中的小错误后,代码将随之出现

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>

您可以在此处观看演示.

这篇关于如何验证具有默认值的可选字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆