Simple Regexp Problem! Plz Help!

Discussion in 'JavaScript' started by natekapi, Jan 28, 2007.

  1. #1
    I'm trying to add something to this short form validation script, to make sure that the telephone number a person is entering does not start with a 1. If it doesnt I need the error message displayed. Right now it only checks to make sure a number is entered. I know the regexp is /^1/ but I couldn't get something right.

    I'm sure its pretty damn easy to someone who knows javascript but I'm just using this code that I found somewhere else so I'm lost.

    function validateForm(form){
       var header = "The following fields are required.\n";
       var message = "";
    
       if(txtmsg.number.value == ""){
       message = message + "* A Mobile Number Is Required.\n";
       txtmsg.number.focus();
       }
    
    }
    </script>
    Code (markup):

     
    natekapi, Jan 28, 2007 IP
  2. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #2
    You can try with somethis like this:
    
    <html>
    <head />
    <body>
    
    <input id="number" name="number" size="10" maxlength="20" value="" /> 
    <button type="button" onclick="JavaScript: f_checkNumber()">Check Number</button>
                  
    <script type="text/javascript">
    
    function f_checkNumber()
    {
    	if ( ! document.getElementById("number").value.match( /^1/ ) )
    		alert( "Mobile Number NOT Detected.\n" );
    	else
    		alert( "Mobile Number Detected.\n" );
    }	
      
    </script>
    
    </body>
    </html>
    
    
    Code (markup):
     
    ajsa52, Jan 28, 2007 IP
  3. natekapi

    natekapi Peon

    Messages:
    527
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I modified your code a little bit and came up with this, which works nicely! Thanks!!!

    
    if (txtmsg.number.value.match( /^1/ ) ){
    	message = message + "* Please Do Not Add A 1 In Front Of The Number!\n";
    	txtmsg.number.focus();
    	}
    Code (markup):
     
    natekapi, Jan 28, 2007 IP
  4. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #4
    If you want your code running outside Explorer (Firefox, Opera, ...) you should use the W3C standard: document.getElementById("number") instead of "whatever.number"
     
    ajsa52, Jan 28, 2007 IP
  5. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #5
    Or if you want it to work on absolutely anything, use
    document.forms.myForm.myElement
    Code (markup):
     
    Logic Ali, Jan 29, 2007 IP