...

View Full Version : js form field validations functions



tech-dudes
01-13-2012, 03:47 PM
use in form fields - onBlur="chkalpha(this)"

function chknum(field) {
var valid = "0123456789";
var ok = "yes";
var temp;
for (var i=0; i<field.value.length && ok == "yes"; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") { var ok = "no"; }
}
if (ok == "no") {
alert("Invalid entry! Only numeric data is accepted!");
field.value=""; field.focus();
field.select();
}
}

function chkalpha(field) {
var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
var ok = "yes";
var temp;
for (var i=0; i<field.value.length && ok == "yes"; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") { var ok = "no"; }
}
if (ok == "no") {
alert("Invalid entry! Only alphabetic data is accepted!");
field.value=""; field.focus();
field.select();
}
}

function chkalphanum(field) {
var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_-. ";
var ok = "yes";
var temp;
for (var i=0; i<field.value.length && ok == "yes"; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") { var ok = "no"; }
}
if (ok == "no") {
alert("Invalid entry! Only alphanumeric data is accepted!");
field.value=""; field.focus();
field.select();
}
}

Philip M
01-13-2012, 04:09 PM
And your question is?

Your code is extremely clumsy and old-fashioned. You should use regular expressions instead.
Alphabetic only will reject Mary-Lou O'Flanaghan in a name field. Numeric only will reject 999-999-999 in a phone number field or 12345-7890 in a zip field.

BTW, when posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.


It is your responsibility to die() if necessary….. - PHP Manual



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum