jQuery 如何检查字母数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5732187/
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-08-26 19:43:31  来源:igfitidea点击:

How to check for alphanumeric characters

jquery

提问by AKor

I'm writing a custom method for a jQuery plugin:

我正在为 jQuery 插件编写自定义方法:

jQuery.validator.addMethod("alphanumeric", function(value, element) {
        return this.optional(element) || (/*contains "^[a-zA-Z0-9]*$"*/);
});

I know the regexp for what I want, but I'm not sure how to write something in JS that will evaluate to True if it contains the alphanumeric characters. Any help?

我知道我想要什么的正则表达式,但我不确定如何在 JS 中编写一些东西,如果它包含字母数字字符,它将评估为 True。有什么帮助吗?

回答by Josiah Ruddell

See testRegExp method.

请参阅testRegExp 方法。

jQuery.validator.addMethod("alphanumeric", function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
}); 

回答by Pablo Hernández - OtakuPahp

If you want to use Spanish chars in your alphanumeric validation you can use this:

如果你想在你的字母数字验证中使用西班牙语字符,你可以使用这个:

jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^[a-zA-Z0-9áéíóúáéíóú?? ]+$/.test(value);
});

I also added a blank space to let users add words

我还添加了一个空格让用户添加单词

回答by Cfreak

You can use regexes in JavaScript:

您可以在 JavaScript 中使用正则表达式:

if( yourstring.match(/^[a-zA-Z0-9]+/) ) {
     return true
}

Note that I used +instead of *. With *it would return true if the string was empty

请注意,我使用了+而不是*. 随着*它会返回true,如果该字符串是空的

回答by Parvez

// use below ... It is better parvez abobjects.com
jQuery.validator.addMethod("postalcode", function(postalcode, element) {
    if( this.optional(element) || /^[a-zA-Z\u00C0-\u00ff]+$/.test(postalcode)){ 
         return false;
    }else{ 
         return this.optional(element) || /^[a-zA-Z0-9]+/.test(postalcode); 
    } 

}, "<br>Invalid zip code");



rules:{
  ccZip:{          
           postalcode : true
       },
       phone:{required: true},

This will validate zip code having no letters but alphanumeric

回答by Eric Frick

$("input:text").filter(function() {
    return this.value.match(/^[a-zA-Z0-9]+/);
})