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 4 of 4

Thread: Validate number

  1. #1
    New Coder
    Join Date
    Apr 2004
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Validate number

    I have a function to make sure a user enters a number. How can I include a number and a comma and period if a user wants to enter a price such as: 9.90?

    The line: [code]if(charVal < "0" || charVal > "9" && charVal != "." && charVal != ",")[code] still prevents a comma and period.

    Code:
    function isNumber2(inputStr, field)
    {
    	for(var i=0; i<inputStr.length; i++)
    	{
    		var charVal = inputStr.substring(i, i+1); 
    		if(charVal < "0" || charVal > "9" && charVal != "." && charVal != ",")
    		{ 
    			alert("Please make sure your " + field + " entry are numbers ., only"); 
    			return false; 
    		}
    	}
    	return true; 
    }
    Robert O.
    Last edited by liorean; 05-27-2004 at 06:44 PM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    var charVal = inputStr;
    if (/[^0-9\.\,]/gi.test(charVal.value) || (charVal.value=="" || charVal.value =="." || charVal.value == ",")) { /// only digits, space, stop or comma allowed, but stop and comma without a digit are invalid

    alert ("Test returned true - match was found"); // i.e. invalid characters are present
    return false;
    }
    return true; // i.e. field contains only valid characters.

  • #3
    New Coder
    Join Date
    Apr 2004
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks Phillip. It works only the opposite of what I was looking for and that's my fault for not explaining things correclty.

    How can the script you sent be revised so that if a customer enters anything BUT 0-9 a comma and a period a alert appears?

    I'm kinda new to JavaScript.

    Robert O.

  • #4
    Senior Coder
    Join Date
    Apr 2003
    Location
    Canada
    Posts
    1,063
    Thanks
    2
    Thanked 0 Times in 0 Posts
    the exact opposite?
    Code:
    var charVal = inputStr;
    if (/[^0-9\.\,]/gi.test(charVal.value) || (charVal.value=="" || charVal.value =="." || charVal.value == ",")) { /// only digits, space, stop or comma allowed, but stop and comma without a digit are invalid
    
    alert ("Test returned true - match was found"); // i.e. invalid characters are present
    return true;
    }
    return false; // i.e. field contains only valid characters.
    Shawn


  •  

    Posting Permissions

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