pantz.org banner
Form validation with Javascript
Posted on 11-03-2002 02:13:00 UTC | Updated on 11-03-2002 02:13:00 UTC
Section: /software/javascript/ | Permanent Link

Below are some examples of doing form validation with Javascript. To be safe your final validation should be done server side. This is because Javascript code is executed client side. As we know we should never trust code the client can modify that we can not verify. You can use Javascript and serverside validation to help keep errors to a minimum and to check for any funny business someone is trying to put in the form fields (sql injeciton). Remember to escape all of those special characters in form fields.

Put all of the code examples from the links below between these script tags.

<script language="JavaScript">
<!--

//-->
</script>

E-Mail format checking script.

if (document.formname.fieldname.value.length > 0) {
  i=document.formname.fieldname.value.indexOf("@")
  j=document.formname.fieldname.value.indexOf(".",i)
  k=document.formname.fieldname.value.indexOf(",")
  kk=document.formname.fieldname.value.indexOf(" ")
  jj=document.formname.fieldname.value.lastIndexOf(".")+1
  len=document.formname.fieldname.value.length

if ((i>0) && (j>(1+1)) && (k==-1) && (kk==-1) && (len-jj >=2) && (len-jj<=3)) {
} else {
  alert("Please enter an exact email address.\n" +
  document.formname.fieldname.value + " is invalid.");
  return false;
  }
}

Check if field has special characters.

var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

  for (var i = 0; i < document.formname.fieldname.value.length; i++) {
  	if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
  	alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
  	return false;
  	}
  }

Check if certian radio buttons have not been selected.

    if (!document.formname.fieldname[0].checked &&
    	!document.formname.fieldname[1].checked &&
    	!document.formname.fieldname[2].checked &&
    	!document.formname.fieldname[3].checked) {
    	alert("Please choose a group designation.\n");
    	return false;
    }

Check if textbox has any characters in it.

     if (document.formname.fieldname.value.length == 0) {
          alert("Please fill out your name.\n");
	  return false;
     }

Check if multiple checkboxes have not been selected.Replace false with true to see if all are selected.

     if (document.formname.fieldname.checked == false &&
         document.formname.fieldname.checked == false &&
	 document.formname.fieldname.checked == false) {
	  
	 alert("Please select at least one checkbox.\n");
	 return false;
     }

Check drop down has been selected. Set drop down's value to Not_Selected for this to work.

     if (document.formname.fieldname.value == 'Not_Selected') {
          alert("Please provide us with a selection.\n");
          return false;
     }

Scan values in a field and if they are all letters then alert. The second block of code does the same but for numbers.

//alert on finding all letters
    var noalpha = /^[a-zA-Z]*$/;
if (noalpha.test(document.formname.fieldname.value)) {
     alert("Please enter at least one number in the \"username\" field.");
     return false;
}

//alert on finding all numbers
var nonums = /^[0-9]*$/;
if (nonums.test(document.formname.fieldname.value)) {
     alert("Please enter at least one letter in the \"username\" field.");
     return false;
}

Remove special characters from a string.

function clearText() {
     document.formname.fieldname.value=filterNum(document.formname.fieldname.value)

     function filterNum(str) {
          re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
          // remove special characters like "$" and "," etc...
          return str.replace(re, "");
     }
}

Detect special characters in text box. Or any character you subsitute for the special characters.

     var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
        for (var i = 0; i < document.formname.fieldname.value.length; i++) {
                if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
                alert ("The box has special characters. \nThese are not allowed.\n");
                return false;
        }
                }

Del.icio.us! | Digg Me! | Reddit!

Related stories


RSS Feed RSS feed logo
About


3com
3ware
alsa
alsactl
alsamixer
amd
apache
areca
arm
ati
auditd
awk
badblocks
bind
bios
bonnie
cable
carp
cat5
cdrom
centos
chart
cifs
cisco
comcast
commands
comodo
compiz-fusion
corsair
cpufreq
cpufrequtils
cpuspeed
cron
crontab
crossover
cu
cups
cvs
database
dd
dd_rescue
ddclient
debian
decimal
dhclient
dhcp
diagnostic
diskexplorer
disks
dns
dos
dovecot
dsniff
dvdauthor
e-mail
editor
emerald
ethernet
ext3
fat32
fedora
fetchmail
fiber
filesystems
firefox
firewall
flexlm
floppy
flowtools
fonts
format
ftp
gdm
gnome
greylisting
growisofs
grub
harddrive
hba
hex
hfsc
html
http
idl
ie
intel
ios
ipmi
iptables
irix
javascript
kde
kernel
kmail
kprinter
krecord
kubuntu
linux
logfile
maradns
matlab
memory
mencoder
mhdd
mkinitrd
mkisofs
moinmoin
motherboard
mouse
movemail
mplayer
multitail
mutt
myodbc
mysql
mythtv
nagios
nameserver
netflow
nic
ntfs
ntp
nvidia
odbc
openbsd
openntpd
openoffice
openssl
opteron
parted
partimage
patch
perl
pf
pfflowd
pfsync
photorec
php
pop3
pop3s
ports
postfix
power
procmail
proftpd
proxy
pxe
python
qemu
r-studio
raid
recovery
router
rpc
rsync
samba
schedule
scsi
seagate
seatools
sendmail
sgi
shell
siw
smtp
snort
solaris
soundcard
spam
spamd
sql
sqlite
squid
ssh
ssl
subnet
subversion
sun
supermicro
switches
symbols
syslinux
systemrescuecd
t1
tcpip
tcpwrappers
telnet
terminal
testdisk
tftp
thttpd
thunderbird
timezone
tools
tr
trac
tuning
tunnel
vi
wget
wiki
windows
windowsxp
wireless
wpa_supplicant
x
xauth
xfree86
xfs
xinearama
xmms
zdump
zic
zlib