javascript正则表达式允许带引号的多个单词
我有一个 ,我需要validation双引号之间的所有内容是纬度还是经度。 我已经设置好这个单词不能使用超过3次,这很好。 但是我有一条错误消息,显示何时使用了错误的格式。 当用户聚焦并且没有在引号之间放置任何内容或者它不是纬度或经度时,我需要弹出错误。
这是我的演示:
小提琴
$('#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:
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'}); } });
参考thg435的评论:
如果您尝试解析无效的json,则抛出SyntaxError
。 查看文档 :
JSON.parse将字符串解析为JSON并返回解析后的值。
…
如果要解析的字符串无效JSON,则抛出SyntaxErrorexception。
示例代码:
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');
这种方法使用下划线
请参阅此处的工作副本: http : //jsfiddle.net/fcvyL/2/