2011-11-11 30 views
3

我想通过比较两个字段来验证2个输入字段,并确保第二个字段大于第一个字段。如何使用jQuery验证器来比较两个字段

我需要添加一个自定义的方法吗?或者我可以在范围方法中使用变量名吗?如果是这样,你能指出我的语法吗?

var validateSection = function (theForm) { 
$(theForm).validate({ 
    rules: { 
     startPoint: { 
      required: true, 
      range: [0, 100] 
     }, 
     endPoint: { 
      required: true, 
      range: [startPoint + 1, 100] //Is this possible if I set the function to run on any change to either field? 
     }, 
} 
}); 

if ($(theForm).valid()) { 
    return true; 
} 
else { 
    return false; 
} 
} 

代码自定义方法:之前,我形成

$.validator.addMethod("endGreaterThanBegin", function(value, element) { 
    return endPoint > startPoint 
}, "* End Point Should be Greater than Start"); 

var validateSection = function (theForm) { 
    $(theForm).validate({ 
     rules: { 
      startPoint: { 
       required: true, 
       range: [0, 100] 
      }, 
      endPoint: { 
       required: true, 
       range: [1, 100], 
       endGreaterThanBegin: true 
      }, 
     } 
    }); 
    if ($(theForm).valid()) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 

获得$ .validator是不确定的,然后validateSection不是一个函数,当我开始测试输入字段

+0

添加的代码试图自定义方法的建议 – jimdrang

回答

11

极品添加custom validate method

Protoype -

$.validator.addMethod("endate_greater_startdate", function(value, element) { 
    return enddate > startdate 
}, "* Enddate should be greater than Startdate"); 

验证 -

endate_greater_startdate : true 

检查的Demo,因为不同的例子,但将帮助调试。

+0

出于某种原因,当我添加此我得到$ .validator是不确定的,然后当我得到到那个页面并开始搞乱那些我得到validateSection的字段不是一个函数。我只是在validateSection函数上面添加它是否有一个特殊的地方需要去? – jimdrang

+0

添加了演示链接。 addmethod的一个例子。 – Jayendra

+0

演示不工作! –

0

的Javascript

$(function() { 
    $.validator.addMethod('smaller_than', function (value, element, param) { 
     return +$(element).val() < +$(param).val(); 
    }); 
    $.validator.addMethod('not_smaller_than', function (value, element, param) { 
     return +$(element).val() > +$(param).val(); 
    }); 
    $('form').validate(); 
}); 

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script> 
<form> 
    value 1 
    <input name="value1" 
      data-rule-smaller_than="[name='value2']" 
      data-msg-smaller_than="value 1 must be smaller than value 2" /><br/> 
    value 2 
    <input name="value2" 
      data-rule-not_smaller_than="[name='value1']" 
      data-msg-not_smaller_than="value 1 must be smaller than value 2"/><br/> 
    <input type="submit"/> 
</form> 

JSFiddle

+0

好主意。如果有一些地方添加信息会更好 –