0

I have a regex that I'm trying use to validate against strings. Trying to catch anything that is not: Upper Case alpha, Number, -, /, does not contain spaces and must be atleast 4 characters long and not exceed 78.

I have validated the regex and know that it works, just can't figure out what's wrong.

So far this is what I have:

var turkey = new RegExp('^(\S[A-Z0-9-/]{4,78})$'); 
if (turkey.test(serialNumber)) {
    alert('pass');
}
else {
    alert('fail');
}

Pass:

AS4345-ADFSF/ASDF-445

D/-F4

/ER45-DFGH334/45-4FS

Fail:

aDF345#SD/fr

45-fg/422 fgs

2SD

g-5

1
  • 1
    Could you add some examples of valid and invalid serial numbers? Commented Dec 17, 2010 at 14:58

2 Answers 2

2

I think you should lose the \S.

The regexp you have now is the same as new RegExp('^(S[A-Z0-9-/]{4,78})$') and matches strings like "S-AWFL/12".

If you would add another backslash (new RegExp('^(\\S[A-Z0-9-/]{4,78})$'), the regexp becomes the same as /^(\S[A-Z0-9-\/]{4,78})$')/. You would then match anything that starts with one character that is not whitespace, and then your 4-78 character code. So "!23ASF-//" would match, but not " 23ASF-//".

Sign up to request clarification or add additional context in comments.

4 Comments

Just edited my post.. I do want to exclude white spaces, that was why I added the '\S'. What I don't understand and am having issues with is where to put the escape characters?
Ok, just remove the \S then. The rest of your regexp already excludes whitespace, since it only includes A-Z, 0-9, -, and /. Also, I don't think you need any escape characters, and you don't even need the parentheses. new RegExp('^[A-Z0-9-/]{4,78}$') will do.
@Avien There's no reason for you to use the string constructor version for the regex; just use the literal version: var turkey = /^...$/;
@Phrogz Ah yes, that too. @Avien However, then you will need the escape character for the /: var turkey = /^[A-Z0-9-\/]{4,78}$/;.
0

By process of elimination anything that has to fall within A-Z, /. or a hyphen (-) are automatically not a white-space character, thus no need to check.

Having said that, your pattern looks correct but you should put the hyphen as the last character in the class or escape it, otherwise regex wants to treat it like a range delimiter.

Something like: ^[0-9A-Z\/-]{4,78}$ should suite your needs.

EDIT: Fixed the regex for use with .NET's RegEx (dropped the grouping characters)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.