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
Add a ment  | 

2 Answers 2

Reset to default 5

Rules 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