admin管理员组文章数量:1332865
I need to add a custom validation on datepicker just like we add custom validations by adding rules in javascript like the one here - jQuery Validate Plugin - How to create a simple custom rule?
But before adding one more custom validator on same element I need to verify if another rule/validator method exists.
How can I check that? I know I can get all rules like -
var rules = $(element).rules();
I need to add a custom validation on datepicker just like we add custom validations by adding rules in javascript like the one here - jQuery Validate Plugin - How to create a simple custom rule?
But before adding one more custom validator on same element I need to verify if another rule/validator method exists.
How can I check that? I know I can get all rules like -
var rules = $(element).rules();
Share
edited Oct 10, 2017 at 9:51
Rory McCrossan
338k41 gold badges320 silver badges351 bronze badges
asked Oct 10, 2017 at 9:39
ShivaniShivani
2167 silver badges22 bronze badges
2
- Please provide some code – Maxim Commented Oct 10, 2017 at 9:40
- I need to add and remove rules like - $(element).rules("remove", "date"); Before adding or removing, I need to check if a validator rule is added like we have a greaterthandate validator. How do I fetch that from the list of rules which I have like - var rules = $(element).rules(); – Shivani Commented Oct 10, 2017 at 10:48
2 Answers
Reset to default 5Rules is a dictionary type which can be fetched like below -
function findProperty(obj, key) {
if (typeof obj === "object") {
if (key in obj) {
return true;
} else {
return false;
}
}
return false;
}
var rules = $(element).rules();
if (rules) {
var isGreater = findProperty(rules, 'greaterthandate');
}
After initialising the validate plugin, all the elements which have rules defined will return an object when you call rules()
on it. This object contains the rule definitions, which you can check, something like this:
$('form').validate()
var fooRequired = $('#foo').rules().required || false;
var barRequired = $('#bar').rules().required || false;
console.log('foo required? ' + fooRequired);
console.log('bar required? ' + barRequired)
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<form>
<input type="text" name="foo" id="foo" data-rule-required="true" />
<input type="text" name="bar" id="bar" />
<button type="submit">Go</button>
</form>
本文标签: jqueryHow to check if a validation rule exists on an element in javascriptStack Overflow
版权声明:本文标题:jquery - How to check if a validation rule exists on an element in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742293199a2448200.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论