javascript 字母数字正则表达式javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7949901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:50:27  来源:igfitidea点击:

alphanumeric regex javascript

javascriptjqueryregex

提问by Saher Ahwal

I am having a problem to get the simple reges for alphanumeric chars only work in javascript :

我在获取字母数字字符的简单 reges 时遇到问题,只能在 javascript 中使用:

var validateCustomArea = function () {
        cString = customArea.val();
        var patt=/[0-9a-zA-Z]/;
        if(patt.test(cString)){
            console.log("valid");
        }else{
            console.log("invalid");
        }
    }

I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string

我在 jquery 的 keyup 事件之后检查文本字段值,但结果不是预期的,我只希望字符串中包含字母数字字符

采纳答案by Saher Ahwal

I fixed it this way

我是这样修的

var validateCustomArea = function () {
        cString = customArea.val();
        console.log(cString)
        var patt=/[^0-9a-zA-Z]/
        if(!cString.match(patt)){
            console.log("valid");
        }else{
            console.log("invalid");
        }
    }

I needed to negate the regex

我需要否定正则表达式

回答by mu is too short

This regex:

这个正则表达式:

/[0-9a-zA-Z]/

will match any string that contains at least one alphanumeric character. I think you're looking for this:

将匹配任何包含至少一个字母数字字符的字符串。我想你正在寻找这个:

/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */

Or possibly this:

或者可能是这样的:

var string = $.trim(customArea.val());
var patt   = /[^0-9a-z]/i;
if(patt.test(string))
    console.log('invalid');
else
    console.log('valid');

回答by Jon Newmuis

Your function only checks one character (/[0-9a-zA-Z]/means onecharacter within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.

您的函数仅检查一个字符(/[0-9a-zA-Z]/表示0-9、az 或 AZ 范围内的任何一个字符),但读取整个输入字段文本。您需要循环此操作或通过说出类似/^[0-9a-zA-Z]*$/. 我建议后者。