MohanaRajesh
MohanaRajesh

Reputation: 51

RegEx: For restricting total length of alphanumeric characters including all the group

I have written the regex for select the alphanumeric characters that should satisfy the following conditions.

  1. it can start either start with a-z or 0-9.
  2. it can have maximum two '-' or maximum two space character.
  3. The length should be 10 excluding the '-' and space.

    /(^([a-z]|[0-9])*)[-\s]?(([a-z]|[0-9])*)[-\s]?(([a-z]|[0-9])*)$/i
    

this will meet the above two conditions but it will selects the string that is more the 10 alphanumeric too.

any thought on this.

Upvotes: 0

Views: 1533

Answers (4)

MohanaRajesh
MohanaRajesh

Reputation: 51

@rv7 added extra checking in your answer

let verify = str => {
  if (validator.test(str)) {
    let len = str.match(extractor).join('').length;
    if (len === 10) {
      if (dashvalidator.test(str)) {
        let dashLength = str.match(dashvalidator).join('').length;
        if (dashLength === 2) {
          console.log('dashvalidator valid')
        } else {
          console.log('dashvalidator Invalid!');
        }
      } else {
        if (spaceValidator.test(str)) {
          str = str.replace(/\s/g, '*');
          let spaceLength = str.match(spaceValidatorHelp).join('').length;
          if (spaceLength === 2) {
            console.log('spaceValidatorHelp valid')
          } else {
            console.log('spaceValidatorHelp Invalid!');
          }
        } else {
          console.log('valid!');
        }
      }
    } else {
      console.log('Invalid!');
    }
  } else
    console.log('Invalid!');
}

let str1 = '24-carat magic';
let str2 = '12 34567 890';

let extractor = /\w+/g;
let validator = /^\w+[\-\s]?\w*[\-\s]?\w*$/;
let dashvalidator = /-/g;
let spaceValidatorHelp = /\*/g;
let spaceValidator = /\s/g;



verify(str1);
verify(str2);

I have added the conditions checking

  1. One '-' and one space not allowed in the string.
  2. It should have no special character or should have two '-' or should have two space character

Upvotes: 0

vrintle
vrintle

Reputation: 5586

The desired result can be achieved more easily by JavaScript String methods.

Details:

  • String.match(RegExp) - extract every character from the String object which satisfies the pattern provided by the RegExp object. Returns an array containing the matches.

  • Array.join(separator) - Joins every item in a String array with the given separator.

(extractor)

  • \w+ - matches 1 or more repetitions of alphanumeric character.

(validator)

  • ^ - matches the start of a string.

  • [\-\s] - matches '-' or ' ' once.

  • \w* - matches 0 or more repetitions of alphanumeric character.

  • $ - matches the end of a string.

let verify = str => {
  if(validator.test(str)) {
    let len = str.match(extractor).join('').length;
    console.log(len == 10 ? 'Valid!' : 'Invalid!');
  } else 
    console.log('Invalid!');
}

let str1 = '24-carat magic';
let str2 = 'Shape of you';

let extractor = /\w+/g;
let validator = /^\w+[\-\s]\w*[\-\s]\w*$/;

verify(str1);
verify(str2);

Upvotes: 2

Poul Bak
Poul Bak

Reputation: 10930

You can use the following regex:

/^(?!(?:.*?[ -]){3,})(?:[a-z0-9][ -]?){1,10}$/

Explanation:

^ starts at start of string

(?! starts a negative look ahead

(?: starts a non capturing Group

.*? look for zero or more of any char (non greedy)

[ -] look for the restricted chars

{3,} look for 3 or more of that Group (negative lookahead)

(?: start a non capturing Group

[a-z0-9][ -]? match one character/digit followed by an optional restricted char

{1,10} match 1 to 10 of that Group

$ match the end of string

The tricks: Using neagtive lookahead will restrict the chars.

Using '(?:[a-z0-9][ -]?)' will count only letters/digit - not the restricted char.

Upvotes: 1

Aaron
Aaron

Reputation: 24812

The following should work :

^[a-z0-9]([^- ]{9}|(?=[^- ]*-[^- ]*$).{10}|(?=[^- ]*-[^- ]*-[^- ]*$).{11}|(?=[^- ]* [^- ]*$).{10}|(?=[^- ]* [^- ]* [^- ]*$).{11})$

That is one character of a-z or 0-9 followed by either :

  • 9 characters that are neither spaces nor dashes
  • 10 characters, exactly one of them being a dash, none of them being a space
  • 11 characters, exactly two of them being dashes, none of them being a space
  • 10 characters, exactly one of them being a space, none of them being a dash
  • 11 characters, exactly two of them being spaces, none of them being a dash

You can try it here.

Of course this is all a bit awful and I would discourage you from using a regex for that validation if you can help it.

Upvotes: 0

Related Questions