4

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();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Shivani
  • 224
  • 5
  • 19
  • Please provide some code – Maxim Oct 10 '17 at 09: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 Oct 10 '17 at 10:48

2 Answers2

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');
}
Shivani
  • 224
  • 5
  • 19
1

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.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 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 Oct 10 '17 at 10:44