Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jun 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    REGEX -What's wrong with this???

    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

  • #2
    Banned
    Join Date
    Nov 2008
    Location
    not found
    Posts
    284
    Thanks
    0
    Thanked 53 Times in 51 Posts
    Quote Originally Posted by jennyWren123 View Post
    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/Cor...ical_Operators

  • #3
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    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.

    Code:
    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
    Last edited by mrhoo; 06-08-2010 at 05:04 AM. Reason: semicolon


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •