What is wrong with JavaScript

I have been down this maddening road before.

I have this code. This is part of the function chk_vals() which is in the form onSubmit="return chk_vals();"
<!-- Property Phone Number -->			
			ph = document.getElementById("prop_phone").value;
			ph = ph.replace(/-/g, "");
			ph = ph.replace(/\./g, "");
			ph = ph.replace(/\(/g, "");
			ph = ph.replace(/\)/g, "");
			if (! isnumeric(ph)) {
				alert ("Invalid phone number.");
				return false;
			}	
			if (ph.length != 10) {
				alert ("Invalid phone number.");
				return false;
			}

Open in new window


and this
function isdigit(test) {
		if (test == "0" || test == "1" || test == "2" ||
	    	test == "3" || test == "4" || test == "5" ||
	    	test == "6" || test == "7" || test == "8" ||
	    	test == "9" || test == ".")
			return true;
		else {
			return false;
	     }
	}
// Function to determine if a field is numeric
	function isnumeric(field) {
		len = field.length;
		for (i = 0; i < len; i++)
			if (isdigit(field.charAt(i)) == false) {
				return false;
			}
		return true;
	}

Open in new window


In the case in point (many) the value of getElementById("prop_phone") is a 10 digit number.

What is wrong?
Richard KortsBusiness Owner / Chief DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael ArciniegaExperts Exchange QACommented:
Sample code/data

What are some examples of entries that do not pass the test?
ste5anSenior DeveloperCommented:
Just a comment: Why not using HTML5 form validation?
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
Example of failure: 6198559192
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Michael ArciniegaExperts Exchange QACommented:
When I plug your code in https://jsfiddle.net/ and run it that test passes.
ste5anSenior DeveloperCommented:
Your methods should work as intended. But when you take my sample and copy the number and paste it into the input, then you will (maybe) see that there is a space at the end. So when I need to guess, you have missed to sanitze the input furthermore and remove spaces.

<!DOCTYPE html>
<html>
    <script language="JavaScript">
        function isdigit(test) {
            if (test == "0" || test == "1" || test == "2" ||
                test == "3" || test == "4" || test == "5" ||
                test == "6" || test == "7" || test == "8" ||
                test == "9" || test == ".")
                return true;
            else {
                return false;
             }
        }

        function isnumeric(field) {
            for (i = 0; i < field.length; i++)
                if (isdigit(field.charAt(i)) === false) {
                    return false;
                }
            return true;
        }

        function checkInput()
        {
            var ph = document.getElementById("prop_phone").value;
            ph = ph.replace(/-/g, "");
            ph = ph.replace(/\./g, "");
            ph = ph.replace(/\(/g, "");
            ph = ph.replace(/\)/g, "");
            ph = ph.trim();
            if (!isnumeric(ph)) {
                alert ("Invalid phone number. 1:" + ph);
                return false;
            }
            if (ph.length != 10) {
                alert ("Invalid phone number. 2");
                return false;
            }
            return true;
        }

        function test()
        {
            var result = document.getElementById("result");
            result.innerHTML = checkInput() ? 'true':'false' ;
        }
    </script>
    <body>
        <form>
            <input id="prop_phone" type="text">6198559192</input>
        </form>
        <button onClick="test()">test</button>
        <div id="result"></div>
    </body>
</html>

Open in new window


p.s. the above would have been a concise and complete example.. posting fragments only is annoying.
leakim971PluritechnicianCommented:
Some shortcut :

<!-- Property Phone Number -->			
	ph = document.getElementById("prop_phone").value;
	ph = ph.replace(/\D/g, "");
	if (ph.length !=10 || isNaN(ph)) {
		alert ("Invalid phone number.");
		return false;
	}
	return true;
}

function isdigit(str) {
	return str*1 === str && str%1 !== 0;
}

function isnumeric(field) {
	return !isNaN(field);
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
I suspect there is an unrelated JavaScript error that effects this. I will check tomorrow with Chrome on the full file.

Thanks.
Julian HansenCommented:
Another variation on the validation
function validPhone(phone)
{
   // Get rid of the valid formatting chars 
   var res = phone.replace(/[\(\)-\.]/g, "");

   // Check if there are any non-digits left
   var m = res.match(/\D/g);

  // If we are left with a 10 character string it is valid
   return !(m || res.length != 10) ;
}

Open in new window

You can test it here
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
Using the original (posted) code, I ran it in Chrome with Javascript debugger turned on, SAME phone #, works fine, NO alert about less than 10.

What now?

I normally develop & debug in FireFox
ste5anSenior DeveloperCommented:
As I wrote. you may have spaces at the end of your number..
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
ste5an,

That is NOT the problem.
ste5anSenior DeveloperCommented:
How should we know that? You haven't posted a concise example showing that behaviour..

Using the original (posted) code
Sorry, these are only fragments. The error maybe triggered by something else. Especially:

This is part of the function chk_vals() [..]
Can you imagine that those unposted parts are the problem?
leakim971PluritechnicianCommented:
Did you try what I posted ? It's just to confirm the part you only show is the issue.
You just need to replace your part by my part
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
leakim971

No, I will today.

Thanks,

Richard
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
To all,

If the code works in Chrome & the alert about > 10 does NOT occur, why does it occur with same data in FireFox.

I ran it in Chrome with F12 (Chrome Javascript debugger) on. No errors.

Richard
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
I can give you access to full site if you give me a private way to communicate it to you; it requires UserID & password.

Thanks
Richard KortsBusiness Owner / Chief DeveloperAuthor Commented:
This works in Firefox!

No clue why, but you got it.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.