2016-08-07 82 views
0

我目前有一个表单,我正在使用jQuery验证器插件进行验证。在表单中,我有一个字段,根据输入的另一个字段,是否需要。jQuery验证不正确

<select name="supportiveServices" id="supportiveServices" style="float: left; margin-left: 20px; width: 30%;"> 
     <option value="">Select One</option> 
     <option value="Accepted">Accepted</option> 
     <option value="Declined">Declined</option> 
    </select> 


<input name= "serviceStartDate" id= "serviceStartDate" type="date" style="width: 50%;"></input> 

jQuery的

serviceStartDate: { 
      required: function(element) { 
       if($("#supportiveServices").val() == 'Accepted') { 
        return true; 
       } 
       else { 
        return false; 
       } 
      }, 

     }, 

这种依赖性要求似乎很好地工作,但我一直运行到的问题是我我需要的日期也有效。我已经添加了一个方法来确保日期有效。

jQuery.validator.addMethod("DateFormat", 
    function(value, element) { 
    return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/); 
}, 
    "Please enter a date in the format dd/mm/yyyy"; 
); 

我是新来这个插件,但我曾尝试以下两种解决方案,它们都返回true,需要输入:

  1. 创建,基本上返回true的函数,如果日期是空的如果不是,则为false。

    serviceStartDate: { 
         required: function(element) { 
          if($("#supportiveServices").val() == 'Accepted') { 
           return true; 
          } 
          else { 
           return false; 
          } 
         }, 
    
         DateFormat: function(element) { 
          if($("#serviceStartDate").val() != 0 || $("#serviceStartDate").val() != null || $("#serviceStartDate").val() != undefined || $("#serviceStartDate").val() != '') { 
           return true; 
          } else { 
           return false; 
          } 
         } 
    
        }, 
    
  2. 创建一个单独的方法。

    jQuery.validator.addMethod("DateFormatSupport", 
         function(value, element) { 
         if ($("#serviceStartDate") == 0) { 
         return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/); 
         } 
        }, 
        "Please enter a date in the format dd/mm/yyyy"//removed ; 
        ); 
    

,并调用它。

 serviceStartDate: { 
      required: function(element) { 
       if($("#supportiveServices").val() == 'Accepted') { 
        return true; 
       } 
       else { 
        return false; 
       } 
      }, 

      DateFormatSupport: true 
      } 

     }, 

基本上,我需要验证,以确保如果客户不选择“接受”的支持性服务,那么serviceStartDate可选配。如果选择“接受”支持服务,则需要填写serviceStartDate并且日期也需要有效。作为预防措施,我想如果他们在serviceStartDate中填写任何内容(无论是否为可选)作为日期 - 这将发送到数据库,因此它必须为空或日期。

有什么建议吗?

+0

您是否尝试过'那已经内置到插件date'规则? – Sparky

回答

0

我想如果他们填写serviceStartDate中的任何东西,无论是否可选,都是约会......有什么建议吗?

你只需要声明内置在你的日期字段date规则,同时使required规则取决于您select元素,你已经做了。在这种情况下,不需要自定义规则。也不需要制定date规则,因为只要可选字段留空,所有规则都会自动忽略。

rules: { 
    supportiveServices: { 
     required: true 
    }, 
    serviceStartDate: { 
     required: function(element) { 
      return ($("#supportiveServices").val() == 'Accepted') ? true : false; 
     }, 
     date: true 
    } 
} 

工作演示:jsfiddle.net/y1Lytetm/

注意

  • 我用ternary shorthand你的条件......这是一个代码行更换六人。

  • 有没有这样的事,作为一个input容器元素,所以我删除您的交易</input>标签,不存在合法的HTML。