首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否仅允许输入字母、数字和连字符?

是否仅允许输入字母、数字和连字符?
EN

Stack Overflow用户
提问于 2017-07-06 02:21:57
回答 2查看 7.5K关注 0票数 1

我希望在输入中只接受字母、数字和连字符(破折号)。在php中,我这样做:

代码语言:javascript
运行
复制
if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
    echo "Only letters, numbers, and hyphens are allowed.";
}

我如何在vanilla javascript中实现同样的功能?如果这在纯javascript中是不可能的,我如何在jquery中做到这一点?谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-06 02:37:36

改编自Sylvain的答案:jQuery only allow numbers,letters and hyphens

注意: jQuery几乎是一个普通js的包装器为了使许多像Document.querySelectorAll()这样的常见语句变得更短,通常可以安全地假设jQuery可以直接转换为普通js (我想不出任何例子来说明jQuery功能的不同)。

您可以做的是选择表单中的所有输入(或您想要的任何输入),然后根据正则表达式测试它们的值(Sylvain使用了一个正则表达式,它选择了所需字符的倒数,因此如果有无效字符,则它将为true ),如果它有任何禁用字符,则阻止表单提交,并执行一些其他操作,要求用户解决该问题。

代码语言:javascript
运行
复制
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;
        }
    }
});
代码语言:javascript
运行
复制
<form id="formWhitelistedChars">
  <input name="1" />
  <input name="2" />
  <button type="submit">Submit</button>
</form>

编辑:将0-9替换为\d,如评论中提到的@ibrahimmahrir

EDIT2:将输入侦听器更改为表单提交

票数 3
EN

Stack Overflow用户

发布于 2017-07-06 02:30:06

您可以使用/{criteria}/{flags}启动一个新的正则表达式。您的正则表达式将转换为如下所示:

代码语言:javascript
运行
复制
/^[aA-zZ0-9-]+$/g.test(/* value to test here*/)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44933411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档