Craig Irlam Craig Irlam - 1 year ago 53
jQuery Question

How to validate a form based on an array of values

I'm looking for the simplest way of validating a form, based on an array of values (this will be serial numbers so I have an array like this : abc123, xyz456, fghqwe, etc stored in a variable )

I have looked into some jQuery / Bootstrap validator plugins but was not able to come up with it.

So the code will check dynamically if a field = any of item in an array then success

I'm using wordpress + bootstrap

regards,
Craig

Answer Source

Hi Craig If you want to validate inputs according to your needs Jquery validate provides custom method support.

You can create your custom method like below

$.validator.addMethod("custom_function_name", function(value, element, param){

and call it from the rule's part of the validate method like below

rules : {
    property_name : custom_function_name
}

In your case you can use custom validation function like below(Sample Code)

HTML :

<form id="testForm">
    <input type="text" name="firstName"/>
    <input type="text" name="lastName"/>
    <input type="submit">
</form>

JQuery :

$("#testForm").validate({
    rules : {
    firstName : {   required : true,
                    presentInList : true
    },
    lastName : {    required : true,
                    presentInList : true
    }
    },

    message : {
    firstName : { required : "Please enter"
    },
    lastName : { required : "Please enter"
    }
    },

     submitHandler: function (form) {
        console.log("Ok");
    }
});


var yourList = ["praksh", "Abhi"]

$.validator.addMethod("presentInList", function(value, element, param){
    if( $.inArray( value, yourList) != -1) {
        return true;
    } else {
        return false;
    }
}, "not in list");

Demo : https://jsfiddle.net/Prakash_Thete/cncLa71b/