如何检查字母数字字符

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

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

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

请参阅test RegExp方法。

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

如果您想在字母数字validation中使用西class牙语字符,可以使用:

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

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

 // 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); } }, "
Invalid zip code"); rules:{ ccZip:{ postalcode : true }, phone:{required: true}, This will validate zip code having no letters but alphanumeric

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

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

请注意,我使用+代替* 。 如果字符串为空,则返回true

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