Results 1 to 2 of 2

Thread: Help!

  1. #1
    Join Date
    Mar 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Help!

    I have an input named address in a form named customerform and am trying to validate that it contains numbers. But if I were to enter 22222 Pine Way it gives the error message, but 67845 Alfa St would work fine because it has two unique numbers. Why do I need two numbers and how can I change this? Here is the script:
    _test_000 = "0"
    _test_00 = "1"
    _test_01 = "2"
    _test_02 = "3"
    _test_03 = "4"
    _test_04 = "5"
    _test_05 = "6"
    _test_06 = "7"
    _test_07 = "8"
    _test_08 = "9"
    address_name = document.customerform.address.value
    if((address_name.indexOf(_test_000) <= 0) && (address_name.indexOf(_test_00) <= 0) && (address_name.indexOf(_test_01) <= 0) && (address_name.indexOf(_test_02) <= 0) && (address_name.indexOf(_test_03) <= 0) && (address_name.indexOf(_test_04) <= 0) && (address_name.indexOf(_test_05) <= 0) && (address_name.indexOf(_test_06) <= 0) && (address_name.indexOf(_test_07) <= 0) && (address_name.indexOf(_test_08) <= 0)) {
    //error message
    }

  2. #2
    Join Date
    Feb 2007
    Location
    England
    Posts
    254
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default

    You really should get in to the habit of using javascripts built-in functions. Regular Expressions, or regExp for short, are convienient functions for searching for strings (words or numbers).

    Code:
    <HTML>
    <HEAD>
    <SCRIPT type="text/javascript">
    	function checkNum(inputId) {
    
    		//get the form object from its ID.
    		inputObj = document.getElementById(inputId);
    
    		//Set up a 'regular expression' to search for 1 or more numbers. '\d' searches for a number, '+' searches for 1 or more occurences 
    		var re = /\d+/;
    
    		//Use the regular expression on the string. In this case the string is the objects value (address.value = 11 parsons drive in this example). If there are numbers then the value of containsNum = true;
    		var containsNum = inputObj.value.match(re);
    
    		//Use the value true or false to determine what to alert to the user.
    		var alertText = containsNum ? "Contains numbers" : "Doesn't contain numbers";
    
    		//alert the user.
    		alert(alertText);
    	
    	}
    </SCRIPT>
    </HEAD>
    <BODY>
     <form id="customerform">
     <input id="address" type="text" value="11 Parsons Drive">
     <input type="button" value="Check" onclick="checkNum('address')">
     </form>
    </BODY>
    </HTML>

Bookmarks

Posting Permissions

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