Reputation: 1025
I have a <textarea>
where I need to validate that everything between double quotes is either latitude or longitude. I have it set up so that the word can not be used more than 3 times which is fine. But I have an error message that shows when the wrong format is used. I need the error to pop up when the user focuses out and hasn't put anything in between quotes or it's not latitude or longitude.
Here is my demo:
$('#test').on('keydown focusout', function(e){
var word = 'latitude',
count = this.value.match(new RegExp('"\\b'+word+'\\b"','g')) || [],
limiter = $('#output');
$('#output').text(count.length);
return !(count.length > 2 && e.which != 8);
});
//Error - Max limit reached
$('#test').bind('keyup focusout', function(){
limiter = $('#output');
if(limiter.text() == '3'){
$('#limitReached').attr("class","hi");
$('#limitReached').text("You cannot exeed more than 10 coorniates");
$('#test').css({'border': '1px solid red'});
}
else{
$('#limitReached').attr("class","bye");
$('#limitReached').text("");
$('#test').css({'border': '1px solid black'});
}
});
//Error - Format is wrong
$('#test').on('focusout', function(e){
var word1 = 'latitude',
word2 = 'longitude',
count = this.value.match(new RegExp('"\\b'+word1+'\\b"','g')) || [];
if ($(this).val() != count){
$('#limitReached').attr("class","hi");
$('#limitReached').html('Please use correct JSON format:<br> example - [{"latitude":33.851871,"longitude":-84.364336},]');
$('#test').css({'border': '1px solid red'});
}
else{
$('#limitReached').attr("class","bye");
$('#limitReached').text("");
$('#test').css({'border': '1px solid black'});
}
});
Upvotes: 0
Views: 455
Reputation: 617
Referring to thg435's comment:
If you try to parse invalid json a SyntaxError
is thrown. See the docs:
JSON.parse parses a string as JSON and returns the parsed value.
...
If the string to parse is not valid JSON, a SyntaxError exception is thrown.
Sample code:
try {
var json = JSON.parse('[{"latitude":33.851871,"longitude":-84.364336}]');
if (json.length > 3) throw new Error("Too many coordinates");
_.each(json, function(coordinate) {
if (!_.has(coordinate, 'latitude') || !_.has(coordinate, 'longitude')) throw new Error("Invalid coordinate pair found");
});
}
catch (e) {
// handle your invalid json and return to stop further execution
console.error(e);
return;
}
console.info('ok');
This approach uses underscorejs
See for a working copy here: http://jsfiddle.net/fcvyL/2/
Upvotes: 3