简体   繁体   中英

Need regular expression to allow maximum of 3 special character

I need a regular expression which fulfills below requirements.

  1. should accept alphanumeric with the length in between 0 to 50 characters
  2. should accept all special characters except ','
  3. should accept minimum of 0 and maximum of 3 special characters.

Tried this, but its not working as expected.

^[a-z\s]{0,50}[.\-']*[a-z\s]{0,50}[.\-']*$

Please let me know, if some one gets this right.

Well, you could either write some monstrous regexp, which would be impossible to read or maintain, or just write code which says what the rules are:

function validate(str) {
    var not_too_long          = str.length <= 50,
        has_no_dots           = !/\./.test(str),
        not_too_many_specials = (str.match(/[^\w\s]/g) || []).length <= 3;

    return not_too_long && has_no_dots && not_too_many_specials;
}

with appropriate adjustments for your definition of "special characters".

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