我需要一个在每个字符都不存在的regexp (a- za - z0 -9_),或者如果字符串只是数字。

时间:2022-02-18 21:15:44

The following JavaScript code returns false if the string contains only numbers or characters other than [a-zA-Z0-9_].

如果字符串只包含[a-zA-Z0-9_]之外的数字或字符,则以下JavaScript代码返回false。

function validate(n) {
    return (!/^[\d]+$/.test(n) && /^[\w]+$/.test(n));
}

Is it possible to do this with just a regexp? I want to take advantage of pattern attributes on the input tag for validation.

仅仅使用regexp是否可能实现这一点?我想利用输入标签上的模式属性进行验证。

<input type="text" pattern="...">

Edit: I also want it to be between 5 and 20 characters

编辑:我还希望它在5到20个字符之间

1 个解决方案

#1


3  

Like this: ^[a-zA-Z0-9_]*[a-zA-Z_]+[a-zA-Z0-9_]*$

[:^ - za - z0 - 9 _]*[a-zA-Z_]+[a-zA-Z0-9_]* $

This regex matches zero or more characters including numbers, at least one character that isn't a number, followed by another zero or more characters including numbers.

这个regex匹配0或多个字符,包括数字,至少一个字符不是数字,后面是另一个0或更多字符,包括数字。

#1


3  

Like this: ^[a-zA-Z0-9_]*[a-zA-Z_]+[a-zA-Z0-9_]*$

[:^ - za - z0 - 9 _]*[a-zA-Z_]+[a-zA-Z0-9_]* $

This regex matches zero or more characters including numbers, at least one character that isn't a number, followed by another zero or more characters including numbers.

这个regex匹配0或多个字符,包括数字,至少一个字符不是数字,后面是另一个0或更多字符,包括数字。