"Hosh" <1@2.com> writes:
[color=blue]
> I have a form on a webpage and want to use JavaScript validation for the
> form fields.[/color]
Ok. First describe, in words, which values are acceptable for which
fields, and what should happen if the values fail to validate.
[color=blue]
> I have searched the web for form validation scripts and have come up with
> scripts that only validate individual fields, such as an "Email Validation
> Script" or a "Phone Validation Script".[/color]
It's dangerous to use other people's validation scripts without
understanding them, because they might not do exactly what you want.
E-mail validation is a case where many scripts you find are too
restrictive, and not accepting a user's e-mail is a pretty sure way
to lose a customer (if one's site has such). Likewise phone number
validation should probably be prepared for foreign numbers as well.
[color=blue]
> Is it ok to put all these scripts on page as they are or should they be
> joined in some way together to be one script?[/color]
Most likely the latter. Each validation script consistes of some
scaffolding that calls the script at certain times, some actual
tests on values, and a response if validation fails. You only
want the scaffolding and response once, but you want a test
for each value that you have requirements for.
[color=blue]
> I'm a total JavaScript newbie and am completely lost.[/color]
Ok, here is a template for making a validation script:
---
<script type="text/javascript">
/* a validation function called when the user tries to submit the form */
function validate(form) {
var success = true;
// for each value to validate:
var field1Value = form.elements['field1'].value;
if (! ... some test on the value ...) {
success = false;
// possibly note which field fails for the user.
}
// end for each
if (!success) {
// tell the user somehow, e.g., alert("Invalid values entered")
// but preferably a more descriptive text.
}
return success;
}
</script>
.....
<form action=".." onsubmit="return validate(this);">
... <input type="text" name="field1" ... > ...
</form>
---
Such a validation script checks only when the user tries to submit.
It's also possible to validate a field as soon as the user leaves it
(or even when he presses a key, but that's usually considered too
intrusive), but what code you need depends on the description you
started out with of what it should do.
Also, never forget that client-side validation is only a convenience
to prevent a server round-trip that would fail anyway. The server must
always validate its input, whether the client does so or not.
/L
--
Lasse Reichstein Nielsen -
lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'