...

View Full Version : REGEX -What's wrong with this???



jennyWren123
06-07-2010, 11:44 PM
Hi - I am trying to use this code to validate,

function test() {
var pattern = (/^\d{3}[-]?\d{2}[-]?\d{4}$/g);
var pattern1 = (/^d{3}$/g);
if(!pattern.test(document.myform.textInput.value)||(!pattern1.test(document.myForm.textInput.value)) )
{
alert("Error!");
}
}

using regular expressions to compare a string from an input with two patterns that could both be valid. Therefore I'm pretty sure I need to use "||" between them both. I can't quite figure out how to get javascript to check for both patterns, only the first seems to be checked as valid. Is it something to do with the way I have my brackets?

Can someone point me in right direction,

Thanks

randomuser773
06-08-2010, 01:24 AM
I can't quite figure out how to get javascript to check for both patterns, only the first seems to be checked as valid.

Can someone point me in right direction,

Thanks

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Expressions_and_Operators#Logical_Operators

mrhoo
06-08-2010, 05:09 AM
If you make the first part of the pattern "^\d{3}" imperative
and the tail optional "([-]?\d{2}[-]?\d{4})?$"
you can test it in one go.

You don't want the g-flag if you are looking for just one match in a string.


function test(){
var s= document.myform.textInput.value;
var pattern= /^\d{3}([-]?\d{2}[-]?\d{4})?$/g;
if(!pattern.test(s)){
alert("Error!");
}
}

123= true
123-45-6789= true
123456789= true
12345-6789= true
12-345-67-89= false



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum