0

I am trying to get my regexp working but I am not having much luck.

I would like to check whether the input string is 6 numbers and 1 character (123123A), no spaces, no dashes. My regex doesn't match even though I think I am entering a valid string.

Could anyone please point me where my issue is?

var userString = "123123A";
if( /^d{6}[a-zA-Z]{1}$/.test(userString) ){
  alert("Correct format");              
}
else{
  alert("Incorrect format");                    
}
4
  • What's the valid username you are typing? Commented Nov 10, 2014 at 20:57
  • put the regexp on the input as a pattern attrib, which works without JS and helps AT. Commented Nov 10, 2014 at 21:04
  • @BustedSanta - I just edited your question to show you how to ask this sort of question in SO. You want to give a really succinct working example, and keep your explanation centered around the actual problem you're having. Commented Nov 11, 2014 at 1:45
  • @smathy - thanks for the tip. I will try to do a better job describing my question the next time. Commented Nov 11, 2014 at 2:35

2 Answers 2

3

For one, your regular expression syntax is incorrect, you want to use the token \d to match digits instead of matching the literal character d six times. You can also drop {1} from your character class, it is not necessary to use here.

if (/^\d{6}[a-zA-Z]$/.test(userString)) { ...
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the clarification. You answer has answered and resolved my issue.
1

You are not checking the value of the input element:

var userString = document.getElementById("username");

Should be

var userString = document.getElementById("username").value;

Also, like hwnd pointed out, you are missing the backslash in the pattern:

/^\d{6}[a-zA-Z]$/

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.