I'm developing some client side form validation that needs to use a JSON file (that is shared with server side validation) that contains arrays of id keys (to describe the input type) and rules (to define what the validation rules are for the input type).
Here is an example of the JSON structure:
[
{
"id": "search",
"rules": [
{
"name": "min_length",
"value": 5
},
{
"name": "email"
}
]
},
{
"id": "phone-number",
"rules": [
{
"name": "min_length",
"value": 5
}
]
}
]
I am doing the following:
- Loading the file and parsing the json and storing as an object.
- Looping through the form and storing all id's.
What I need help with
Match each form element "id" with a corresponding "id" value in the json object
Create a function for each "rules" "name".
When a form element with an "id" that is matched in the JSON object, run the functions that match each "rules" "name" for the matched "id". So looking at the JSON I have above I would want to" Check the form for an element with "search" and then run a function to check the min length and run a function that checks the email (check against a regex I have).
Ideally I want to keep this as generic as possible to allow for any id + rules to be dealt with. The rules themselves will be a pre defined list of "min_length", "email" etc so these can be functions that run if the rule exists.
Here is some JS code that I have so far. It's more of a few ideas that haven't got me closer to what I need to do!
// Get the json file and store
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'js/rules.json');
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
// Load json...
loadJSON(rulesData);
// Global vars...
var rules = [];
function rulesData(data) {
// Parse json and create object...
var jsonObj = JSON.parse(data);
// Push objects to rules array for later use
for (var i = 0; i < jsonObj.length; i++) {
rules.push(jsonObj[i]);
}
}
$(function(){
$('#email-submit').click(function(){
var formInputs = new Array();
//Get the form ID
var id = $(this).parent().attr('id');
$('#' + id + ' input').each(function(){
//Get the input value
var inputValue = $(this).val();
//Get the input id
var inputId = $(this).attr('id');
//Add them to the array
formInputs[inputId] = inputValue;
});
console.log(formInputs);
return false;
});
});
var emailRegex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$";