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;
        }
                }

Reddit!

Related stories


RSS Feed RSS feed logo

About


3com

3ware

alsa

alsactl

alsamixer

amd

android

apache

areca

arm

ati

auditd

awk

badblocks

bash

bind

bios

bonnie

cable

carp

cat5

cdrom

cellphone

centos

chart

chrome

chromebook

cifs

cisco

cloudera

comcast

commands

comodo

compiz-fusion

corsair

cpufreq

cpufrequtils

cpuspeed

cron

crontab

crossover

cu

cups

cvs

database

dbus

dd

dd_rescue

ddclient

debian

decimal

dhclient

dhcp

diagnostic

diskexplorer

disks

dkim

dns

dos

dovecot

drac

dsniff

dvdauthor

e-mail

echo

editor

emerald

encryption

ethernet

expect

ext3

ext4

fat32

fedora

fetchmail

fiber

filesystems

firefox

firewall

flac

flexlm

floppy

flowtools

fonts

format

freebsd

ftp

gdm

gmail

gnome

google

gpg

greasemonkey

greylisting

growisofs

grub

hacking

hadoop

harddrive

hba

hex

hfsc

html

html5

http

https

hulu

idl

ie

ilo

intel

ios

iperf

ipmi

iptables

ipv6

irix

javascript

kde

kernel

kickstart

kmail

kprinter

krecord

kubuntu

kvm

lame

ldap

linux

logfile

lp

lpq

lpr

maradns

matlab

memory

mencoder

mhdd

mkinitrd

mkisofs

moinmoin

motherboard

mouse

movemail

mplayer

multitail

mutt

myodbc

mysql

mythtv

nagios

nameserver

netflix

netflow

nginx

nic

ntfs

ntp

nvidia

odbc

openbsd

openntpd

openoffice

openssh

openssl

openvpn

opteron

parted

partimage

patch

perl

pf

pfflowd

pfsync

photorec

php

pop3

pop3s

ports

postfix

power

procmail

proftpd

proxy

pulseaudio

putty

pxe

python

qemu

r-studio

raid

recovery

redhat

router

rpc

rsync

ruby

saltstack

samba

schedule

screen

scsi

seagate

seatools

sed

sendmail

sgi

shell

siw

smtp

snort

solaris

soundcard

sox

spam

spamd

spf

spotify

sql

sqlite

squid

srs

ssh

ssh.com

ssl

su

subnet

subversion

sudo

sun

supermicro

switches

symbols

syslinux

syslog

systemd

systemrescuecd

t1

tcpip

tcpwrappers

telnet

terminal

testdisk

tftp

thttpd

thunderbird

timezone

ting

tls

tools

tr

trac

tuning

tunnel

ubuntu

unbound

vi

vpn

wget

wiki

windows

windowsxp

wireless

wpa_supplicant

x

xauth

xfree86

xfs

xinearama

xmms

youtube

zdump

zeromq

zic

zlib