Forum Moderators: open

Message Too Old, No Replies

The usual JS Validation - Phone Number

How to do so when you break up the Phone #

         

thaedge

4:36 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



As usual, a simple validation with JS has me stumped. While breaking up the phone number looks very nice on the form, validating it has become a pain for me.

Since going to format *3 seperate form fields* (555) - 555 - 5555 I have been unable to figure out how to validate. The form fields are only for the actual telephone number i.e.
( <form input> ) <form input> - <form input>

Anyone know of a script that can easily validate this and be sure there are no letters/gibberish in them? I have it working where it catches everything... but due to the way I got it to work it thinks even a correct phone # is wrong.

Mucho thanks to whoever solves my headache :)

Bernard Marx

5:26 pm on Mar 1, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<html>
<head><title>Validate</title>
<script>

String.prototype.trim = function(){ return this.replace(/^\s+¦\s+$/g,'')}

function validate(form)
{
/* params */
var errorColour = "#FF9999";
var names =
{
phone0: /^\d\d\d$/,
phone1: /^\d\d\d$/,
phone2: /^\d\d\d\d$/
}
/* vars */
var colour, firstError;
var name, elm;

/*check valid*/
for(name in names){
elm = form.elements[name];
if(!names[name].test( elm.value.trim() ) ){
elm.style.backgroundColor = errorColour;
firstError = firstError¦¦elm; /* <--!replace ¦¦ with unbroken pipes! */
}
else
elm.style.backgroundColor = '';
}
if(firstError) firstError.select();
return!firstError;
}
/*---------------------------------
Reg-
^: start
$: end
\d: digit
---------------------------------*/
</script>
</head>
<body>

<form onsubmit="return validate(this)">
<fieldset style="width:500px;padding:10px;">
<legend>Phone</legend>
( <input type="text" name="phone0" size="3"> )
<input type="text" name="phone1" size="3">
<input type="text" name="phone2" size="4">
</fieldset>
<br>
<input type="submit" value="submit">
</form>

</body>
</html>

thaedge

8:00 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



Thanks Bernard... that just cured a huge pain in the arse for me.