[英]javascript regex allow multiple words with quotes
我有一個<textarea>
,我需要驗證雙引號之間的所有內容是緯度還是經度。 我進行了設置,以使單詞不能使用超過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:<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'});
}
});
參考thg435的評論:
如果您嘗試解析無效的json,則會引發SyntaxError
。 見文檔 :
JSON.parse將字符串解析為JSON並返回解析后的值。
...
如果要解析的字符串不是有效的JSON,則拋出SyntaxError異常。
樣例代碼:
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');
這種方法使用underscorejs
請參閱此處以獲取工作副本: http : //jsfiddle.net/fcvyL/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.