我試圖讓英文字母,數字值只有下列字符:正則表達式字母數字和一些某些特殊字符
- # $ % & * () [ ] , ./- _ +
我設法想出下面的代碼
<form id="accountForm" action="">
<input type="text" name="my_input">
</form>
$(function() {
$.validator.addMethod("accept", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
}, 'Only English is allowed');
$("#accountForm").validate({
rules: {
my_input : {
required: true,
accept: '[[email protected]%#&()/+*$,._\\-]+$'
}
}
});
});
但也存在一些問題:
- 如果我嘗試添加
[ ]
代碼完全停止工作 - 如果我添加其他字符或不在上面的列表中,在任何字母后它不顯示任何錯誤消息。例如:ABC你好
- 如果我輸入一個字母,它會給出一個錯誤。
這裏是我的代碼演示:https://jsfiddle.net/w2p1rdbd/1/
能否請你告訴我怎麼解決這個問題?
非常感謝!
爲什麼你要在accept方法中操作正則表達式('new RegExp(「。」+ param +「$」)')?您將以'。[a-zA-Z0-9 @%#&()/+*$,._\--] + $$'作爲正則表達式。我在你的例子中刪除了'.'和'$',添加了'^'並且它似乎正在工作。 [檢查此](https://jsfiddle.net/w2p1rdbd/2/)。 – ClasG