^
|
|
|
javascript noob

Hi there

I have the following script that strips out acceptable non-numeric characters that you would find in a telephone number and then checks to see if it is equal to ten digits. The problem I have is that I can't figure out how I would check for illegal non-numeric characters (characters you wouldn't find in a telephone number).

if (isNaN(strng)) {
		var stripped = strng.replace(/[\(\)\.\-\ ]/g, "");
		if (stripped.length !10) {
		error = "The tel number is the wrong length.\n";	
		}
	}

At the moment, if you enter an illegal non-numeric charater the error "The tel number is the wrong length.\n"; pops up which is understandable because the length of stripped would be more than 10 characters but this would clearly confuse the user.

Any help would be appreciated

I managed to solve my problem by changing my script to the following:

function checkTel (strng) {
var error = "";
var stripped = strng.replace(/[\(\)\.\-\ ]/g, "");
var illegalChars = strng.replace(/[\(\)\.\-\ \0-9]/g, "");  //strips out the acceptable characters you'd find in a tel number, leaving any illegal characters.
	if (strng == "") {
   	error = "Please enter your cell number.\n";
	}
	else if (illegalChars.length != 0) {  //if the length of the variable illegalChars isn't 0 then it contains illegal characters and shows the error msg.
       	error = "The tel number contains illegal characters.\n";
	}	
	else if (stripped.length !=10) {  //if the tel number is not 10 digits long then show error msg.
		error = "The tel number is the wrong length.\n";
	}
return error;
}

I initially thought I had solved my problem but I have proven myself otherwise.

The code below doesn't seem to eliminate non-numeric characters. I can still enter !#$%&* into the input field. The only characters I want to be entered are ().-+ along with spaces and numbers

var illegalChars = strng.replace(/[\(\)\.\-\ \0-9\+]/g, "");

EDIT: Solved my problem. Changed the above line to:

var illegalChars = strng.replace(/[0-9]/g, "");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.