简体   繁体   中英

javascript check if string contains only alphanumeric characters + other special characters

I have found this function to check if a string only contains alphanumeric characters:

function test ( value ) {
 if( value.match("^[a-zA-Z0-9]*$")){
   alert('ok');
 }
}
test( 'Somevalue123' );

Now I would like to improve the above function to allow some other "special characters" like:

  (empty space)
' (single quote)
- (hyphen)
èàùìòÈÀÒÙÌéáúíóÉÁÚÍÓëäüïöËÄÜÏÖêâûîôÊÂÛÎÔç

And some symbols, like:

'_', '&', '.', ',', ':', '(', ')', '[', ']', '/', '+', '=', '?', '#', '@'

So I have try to update it and I was able to do so:

function test ( value, numbers, symbols ) {
 numbers = ( typeof numbers  === 'undefined' ) ? 0 : 1; // default numbers not allowed
 symbols = ( typeof symbols === 'undefined' ) ? 0 : 1; // default symbols not allowed
 value = value.replace(/è|à|ù|ì|ò|È|À|Ò|Ù|Ì|é|á|ú|í|ó|É|Á|Ú|Í|Ó|ë|ä|ü|ï|ö|Ë|Ä|Ü|Ï|Ö|ê|â|û|î|ô|Ê|Â|Û|Î|Ô|ç/g, '' ); // remove allowed characters before check

 // value = value.replace(/...???.../g, '' ); allow white space, single quote and symbols?

 if( numbers == 1 && value.match("^[a-zA-Z0-9 ]*$")){ alert('ok'); } // number allowed
 else if( value.match("^[a-zA-Z ]*$")){ alert('ok'); } // number not allowed
}

Not sure how to allow white space, single quote and symbols (with Regex or value.replace() is the same for me).

Use character class and add all the whitelisted characters in the character class. Make sure the hyphen - is escaped by preceding it with backslash \\- or added at the beginning or end in the character class.

/^[a-zA-Z0-9 èàùìòÈÀÒÙÌéáúíóÉÁÚÍÓëäüïöËÄÜÏÖêâûîôÊÂÛÎÔç'-]*$/

Also, use RegExp#test instead of String#match

function test(value) {
    if (/^[a-zA-Z0-9 èàùìòÈÀÒÙÌéáúíóÉÁÚÍÓëäüïöËÄÜÏÖêâûîôÊÂÛÎÔç'-]*$/.test(value)) {
        alert('Ok');
    }
}

You can try something like this:

/^[a-z0-9-\'_\.,:\(\)&\[\]\/+=\?#@ \xC0-\xFF]+$/i

Logic

  • /a-z0-9/i will handle alphanumeric characters
  • \\xC0-\\xFF will handle foreign character
  • For symbols, you can list them individually.

An alternate could be listing all characters that are not allowed and use negate regex like

/^[^!~`\>\<]$/gi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM