简体   繁体   中英

How to check if a validation rule exists on an element in javascript

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();

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.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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM