Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rexex Phone Validation Not Functioning

Status
Not open for further replies.

dougcranston

Technical User
Oct 5, 2001
326
US
Having a problem with trying to get a regular expression to successfully and correctly validate a field on an HTML form.

Script was sourced from a site that included a test routine, and it successfully worked there. However, it fails to work correctly.

Function is called, and gets to just before the .test of the regex, but then ALWAYS appears to return a "true".

Simply testing a string of non numbers such as: aasdf does not fail.

Any suggestions would be greatly appreciated. I suspect it is a simple issue of my shooting myself in the foot.

Running IE 5.50x 128bit encryption.


Thanks in advance.

Dougc

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Untitled</title>

<script language="javascript" type="text/javascript">
<!--
function getLabelForId(id) {
var label, labels = document.getElementsByTagName('label');
for (var i = 0; (label = labels); i++) {
if (label.htmlFor == id) {
return label;
}
}
return false;
}

function Text_phone(strng) {
var nstr = "";
nstr = strng;

var re = new RegExp("((\(\d{3}\) ?)|(\d{3}[- \.]))?\d{3}[- \.]\d{4}(\s(x\d+)?){0,1}$");
alert("got to textphone passed the regexp."); // debugging
if (nstr.value.test(re)){
alert("got to textphone passed."); // debugging
return true;
} else {
alert("got to textphone failed."); // debugging
return false;
}
}

function validate() {

if(!Text_phone(document.myForm.Textbox)) {
var formfield = document.getElementById('Textbox');
var label = getLabelForId('Textbox');
alert('You must provide a valid phone number including area code.');
label.className = 'problem';
document.myForm.Textbox.focus();
return false;
}
else {
var formfield = document.getElementById('Textbox');
var label = getLabelForId('Textbox');
label.className = 'completed';
return true;
}
} // close function

//-->
</script>
</head>

<body>
<form name="myForm" onsubmit="return validate();" method="post">
<label class='required' for='Textbox'>Phone#: </label><input type='text' id="Textbox" name="Textbox"><br />
<input type="submit">
</form>

</body>
</html>
 
Closed it myself.

Tried so many combinations, and I think that was what shot me in the foot.

Problem was the test function.

A number of the examples I had seen used string.test(regex)

What actually works is: regex.test(string)

Thanks anyways.

Dougc
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top