match entire string (regular expression & javascript)

G

GreggTB

Hello, I'm trying to perform a very simple validation of user input. I
want to verify that the user entered a six-digit string consisting
entirely of numbers. So anything from 000000 to 999999 is considered
valid. The problem that I'm having is getting the validation to work on
the entire string. In other words, 000000 is okay but 000000000000 is
also returning as a match. Here's a quick code block...I have something
along these lines....

/****************************************************/
<html>
<body>
<INPUT name="txtNumberField" type="text" id="txtNumberField">
<INPUT onClick="fnTestNumberField()" id=Button1 type=button value="Test
Number!" name=btnTest>
<script language=javascript>
function fnTestNumberField()
{
var sNumberValue = document.getElementById("txtNumberField").value;

if (sNumberValue.match(/\A[0-9]{6}\z/))
{
alert("match");
} else {
alert("no match");
}
}
</script>
</body>
</html>
/****************************************************/

That is failing when I enter 123456 into the textbox. Why, though? I
know I can replace...

if (sNumberValue.match(/\A[0-9]{6}\z/))

....with something like...

if (sNumberValue.length == 6 && sNumberValue.match(/[0-9]{6}/))

....or I could assign a maxlength to the input box, of course. The thing
is, I really want to know WHY the regular expression isn't responding
as I'd expect. Is there a syntax error somewhere in the code?

Any suggestions would be appreciated. Thanks!
 
R

Random

GreggTB said:
Hello, I'm trying to perform a very simple validation of user input. I
want to verify that the user entered a six-digit string consisting
entirely of numbers. So anything from 000000 to 999999 is considered
valid. The problem that I'm having is getting the validation to work on
the entire string. In other words, 000000 is okay but 000000000000 is
also returning as a match. Here's a quick code block...I have something
along these lines....

/****************************************************/
....

if (sNumberValue.match(/\A[0-9]{6}\z/))
{
alert("match");
} else {
alert("no match");
}
}


Use ^ to match the beginning of the string and $ to match the end.
Also, \d is the same as [0-9].
/^[0-9]{6}$/ or /^\d{6}$/

Both work.
 
G

GreggTB

Excellent! I knew there had to be a way to do that but I'm (obviously)
really new to regular expressions. Thank you so much!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top