How to check for alphanumeric characters

前端 未结 5 1438
南笙
南笙 2020-12-08 22:58

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

jQuery.validator.addMethod(\"alphanumeric\", function(value, element) {
        return this.optional(elemen         


        
相关标签:
5条回答
  • 2020-12-08 23:11

    See test RegExp method.

    jQuery.validator.addMethod("alphanumeric", function(value, element) {
            return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
    }); 
    
    0 讨论(0)
  • 2020-12-08 23:12
    // 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
    
    0 讨论(0)
  • 2020-12-08 23:12
    $("input:text").filter(function() {
        return this.value.match(/^[a-zA-Z0-9]+/);
    })
    
    0 讨论(0)
  • 2020-12-08 23:23

    You can use regexes in 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

    0 讨论(0)
  • 2020-12-08 23:26

    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

    0 讨论(0)
提交回复
热议问题