BustedSanta
BustedSanta

Reputation: 1388

Javascript regexp validation not working

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");                    
}

Upvotes: 0

Views: 86

Answers (2)

hwnd
hwnd

Reputation: 70750

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)) { ...

Upvotes: 3

Garcia Hurtado
Garcia Hurtado

Reputation: 971

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]$/

Upvotes: 1

Related Questions