i’m looking for a solution to validate the input of a textfield against an array which is provided by a json-file.
For example: To check within a registration form, if the desired username already exists.
Can anybody help out with a working example, plugin, script, or tutorial?
The ‘usernames.json’ looks like this…
{"usernames":["carl","jack","jill"]}
…and is read out with…
$.getJSON("usernames.json", function(names) {
var invalidName = names;
I would go on with…
jQuery.validator.addMethod
…but from here on, i’m stuck.
If anybody may help out with a working example, i’d be very glad!
////////////////////////////////////////////////////
EDIT: Thanks to Utkanos and Pavel Staseljun, i could figure out the following solution, which is only roughly tested!
Please also find Utkanos’ example down below, because this one includes “keyup”-handling instead of “submit” and does not include a “required”-check.
“#errorresponse” is the div, where an error-message may be displayed.
$.ajax({
url: "http://yoururlto.json?callback=?",
dataType:"jsonp",
jsonpCallback: '?',
async: false,
success: function(json) {
$('#user').keyup(function(evt) {
var jsonarray = json.usernames;
var userinput = $('#user').val().toLowerCase()
var check = $.inArray(userinput, jsonarray);
if (check !== -1) {
$("#errorresponse").text('Thanks to Utkanos and Pavel Staseljun!');
}
})
}
});
HTML
JS / jQuery