Prem
Prem

Reputation: 5974

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.

Upvotes: 0

Views: 188

Answers (1)

user663031
user663031

Reputation:

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".

Upvotes: 4

Related Questions