【问题标题】:jQuery validate select box with HTML valuejQuery验证带有HTML值的选择框
【发布时间】:2013-03-13 12:53:15
【问题描述】:

我正在使用 jQuery Validation Plugin 进行表单验证,但我无法使用文本字段而不是值字段来验证选择框..

这是我的情况:

[HTML]

<form id="form">
      <select name="customPrice[0][50]" id="customPrice050">
                <option value="2435">Select date... </option>
                <option value="474">Friday, Mar 1st</option>
                <option value="475">Friday, Mar 8th</option>
                <option value="476">Friday, Mar 15th</option>
      </select>
      <br/>
      <input type="submit" value="Click" />

[jQuery]

$(document).ready(function()
{       
 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg != value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   "customPrice[0][50]": { valueNotEquals: "2435" }
  },
  messages: {
   "customPrice[0][50]": {
    valueNotEquals: "Please select a date!"
   }
  }  
 });

 }

);

这很好用。问题是值 2435 不是静态的,它总是在变化。唯一的静态属性是文本“选择日期...”。 现在我想:

"customPrice[0][50]": { textNotEquals: "Select date... " }

有人可以帮我吗?

【问题讨论】:

  • 如果您使用的是最近的 jQuery,您可以制定一个规则来检查您选择的选定索引是否大于 0 $(...).prop("selectedIndex") > 0 @987654321 @
  • @politus - 这是个好主意。比依赖第一个选项的文本要好得多。

标签: jquery jquery-validate


【解决方案1】:

回调函数的中间参数是被验证的元素。您应该能够使用它从所选选项中获取文本并检查它是否不是“选择日期...”。

试试这个:

$.validator.addMethod("selectTextNotEquals", function(value, select, arg) {
    return arg != $(select).find('option:selected').text();
}, "Text must not equal arg.");

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    相关资源
    最近更新 更多