我希望在输入中只接受字母、数字和连字符(破折号)。在php中,我这样做:
if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
echo "Only letters, numbers, and hyphens are allowed.";
}
我如何在vanilla javascript中实现同样的功能?如果这在纯javascript中是不可能的,我如何在jquery中做到这一点?谢谢
发布于 2017-07-06 02:37:36
改编自Sylvain的答案:jQuery only allow numbers,letters and hyphens。
注意: jQuery几乎是一个普通js的包装器为了使许多像Document.querySelectorAll()这样的常见语句变得更短,通常可以安全地假设jQuery可以直接转换为普通js (我想不出任何例子来说明jQuery功能的不同)。
您可以做的是选择表单中的所有输入(或您想要的任何输入),然后根据正则表达式测试它们的值(Sylvain使用了一个正则表达式,它选择了所需字符的倒数,因此如果有无效字符,则它将为true
),如果它有任何禁用字符,则阻止表单提交,并执行一些其他操作,要求用户解决该问题。
document.getElementById("formWhitelistedChars").addEventListener("submit", function(e) {
// Get all inputs in the form we specifically are looking at, this selector can be
// changed if this is supposed to be applied to specific inputs
var inputs = document.querySelectorAll('#formWhitelistedChars input');
var forbiddenChars = /[^a-z\d\-]/ig;
// check all the inputs we selected
for(var input of inputs) {
// Just in case the selector decides to do something weird
if(!input) continue;
// Check that there aren't any forbidden chars
if(forbiddenChars.test(input.value)) {
// This line is just to do something on a failure for Stackoverflow
// I suggest removing this and doing something different in application
console.log('input ' + input.name + ' has forbidden chars.');
// Do stuff here
// Prevent submit even propagation (don't submit)
e.preventDefault();
return false;
}
}
});
<form id="formWhitelistedChars">
<input name="1" />
<input name="2" />
<button type="submit">Submit</button>
</form>
编辑:将0-9
替换为\d
,如评论中提到的@ibrahimmahrir
EDIT2:将输入侦听器更改为表单提交
发布于 2017-07-06 02:30:06
您可以使用/{criteria}/{flags}
启动一个新的正则表达式。您的正则表达式将转换为如下所示:
/^[aA-zZ0-9-]+$/g.test(/* value to test here*/)
https://stackoverflow.com/questions/44933411
复制相似问题