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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validate for numbers and "-" only (phone numbers) 1

Status
Not open for further replies.

4midori

Programmer
Jan 15, 2003
9
US
Hi,

I know this is simple, but I haven't found a script that will work.

I need a script that will allow online 01234567890 and the "-" character in a form field. It should be dynamic so I can pass in the form name and the field name. I will use it either with onblur="phoneNumCheck(this);" or run it with other functions when the form is submitted.

Thanks,

Ben
 
4midori,

Give this a spin, just change this {7,} to a "+" if you don't want at least seven digits.
The "+" will set it to look for 1 or more digits.

Code:
<html><head><script>
function ckphn(frm){
obj = frm.Pnum;
tstval = obj.value;
re = /^[0-9\-]{7,}$/;
if(!tstval.match(re)) {
alert(&quot;Please Enter Your Phone Number&quot;);
obj.focus();
return false; }
else {  return true;  }
}
</script></head><body>
<form name=&quot;test&quot; onSubmit=&quot;return ckphn(this)&quot;>
<input type=&quot;text&quot; size=&quot;10&quot; name=&quot;Pnum&quot; onBlur=&quot;ckphn(this.form)&quot;>
<input type=&quot;submit&quot; value=&quot;Submit&quot;></form></body></html>

2b||!2b
 
Thanks. I tried the code below, but am getting errors. I need code that will dynamically check the field that calls the function.
Code:
function checkPhone(fld){
obj = window.document.forms[0].+fld;
document.write(obj);
tstval = obj.value;
re = /^[0-9\-&quot; &quot;]$/;
if(!tstval.match(re)) {
alert(&quot;Please Enter Your Phone Number&quot;);
obj.focus();
return false; }
else {  return true;  }
}

<form ...>
<input type=&quot;text&quot; name=&quot;BusPhoneAC&quot; class=&quot;Regular&quot; size=&quot;3&quot; maxlength=&quot;3&quot; value=&quot;&quot; onblur=&quot;checkPhone('BusPhoneAC');&quot; />
 
Some adjustments made give it a try:

Code:
<html><head><script>
function checkPhone(fld){
obj = fld;
alert(obj.name);
tstval = obj.value;
re = /^[0-9\-\s]*$/;
if(!tstval.match(re)) {
alert(&quot;Please Enter Your Phone Number&quot;);
obj.focus();
return false; }
else { 
alert(&quot;Finally&quot;);
return true; }
}
</script></head><body>
<form name=&quot;test&quot;>
<input type=&quot;text&quot; name=&quot;BusPhoneAC&quot; class=&quot;Regular&quot; size=&quot;10&quot; 
onblur=&quot;checkPhone(this);&quot; />
</form<</body></html>

2b||!2b
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top