Form Validation
javascript
document.getelementbyid
If you want to quickly access the value of
an HTML input give it an id to make your life a lot easier. This small
script below will check to see if there is any text in the text field
"myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.
JavaScript Code:
<script type="text/javascript">
function notEmpty(){
var myTextField = document.getElementById('myText');
if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />
Display:
document.getElementById returned a reference to our HTML element myText. We stored this reference into a
variable, myTextField, and then used the valueproperty that all input elements have to use to grab the
value the user enters.
There are other ways to accomplish what the above script does, but
this is definitely a straight-forward and browser-compatible approach.
things to remember about getelementbyid
When using the getElementById function, you need to remember a few
things to ensure that everything goes smoothly. You always need to remember
thatgetElementById is a method (or function) of the document object. This means you can only access it
by using document.getElementById.
Also, be sure that you set your HTML elements' id attributes if
you want to be able to use this function. Without an id, you'll be dead in the
water.
If you want to access the text within a non-input HTML element,
then you are going to have to use the innerHTML property instead of value. The next lesson goes into more detail
about the uses of innerHTML.
Form Validation
One of the primary reasons JavaScript was
assembled was to check whether the values entered into forms by readers were correct, thereby bypassing the lengthy trip to a
CGI program to do the check. Here we'll learn the methods used to validate form input, using the
onSubmit
event handler.
Validating Form Input
When you
submit a form to a CGI program that resides on the server, it is usually
programmed to do its own check for errors. If it finds any it sends the page
back to the reader who then has to re-enter some data, before submitting again.
A JavaScript check is useful because it stops the form from being submitted if there is a problem, saving lots of
time for your readers.
The CGI
script is still more reliable, as it always works regardless of whether JavaScript is enabled on the
client-side or not; but having this extra safety barrier is a nice thing to
have in place. It makes your page much more user-friendly, and takes out the
frustration of having to fill out the same form repeatedly. It's also very precise, as you can point out the
exact field where there's a problem.
Implementing the Check
We're
going to be checking the form using a function, which will be activated by the form's
submit
event — therefore, using the onSubmit
handler. Add an
attribute like this to the formyou wish to validate:<
form action="script.cgi"
onSubmit="return
check
form()">
Where
check
Form is the name of the function we're about to create. If you've
learnt your functions properly, you should be able to guess that our function
will return
a Boolean value — either true
or false
. Submit
's default action is to submit the data, but if you give onSubmit
a value of return
false
, it will not be submitted; just like how we can stop a link
from being followed. Of course, if there are no problems, the function call
will be replaced by true
and the data will be
submitted. Simple...
It's
impossible for me to give you a definitive validation script, as every form is different, with a different structure and different values to
check for. That said, it is possible to give you the basic layout of a script,
which you can then customise to the needs of your form.
A general
script looks like this:
{
if (value of first field is or isn't something)
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
else if (value of next field is or isn't something)
{
// something else is wrong
alert('There is a problem with...');
return false;
}
// If the script gets this far through all of your fields
// without problems, it's ok and you can submit the form
return true;
}
If your form is quite complex your script will grow proportionally longer
too, but the fundamentals will stay the same in every instance — you go through
each field with
if
andelse
statements, checking the inputted values
to make sure they're not blank. As each field passes the test your script moves
down to the next.
If there
is a problem with a field, the script will
return
false
at that point and stop working, never reaching the final return
true
command unless there are no problems at all. You should of
course tailor the error messages to point out which field has the problem, and
maybe offering solutions to common mistakes.
Accessing Values
Having
read the Objects and Properties page, you should now know how to find out the values of form elements through the DOM. We're going to be using the
name
notation instead of using numbered indexes to access the elements, so that you are
free to move around the fields on your page without having to rewrite parts of
your script every time. A sample, and simple, form may look like this:<
form name="feedback" action="script.cgi"
method="post" onSubmit="return check
form()">
<input type="text"
name="name">
<input type="text"
name="email">
<textarea
name="comments"></textarea>
</
form>
Validating
this form would be considerably simpler than one containing radio buttons
or select boxes, but any form element can be
accessed. Below are the ways to get the value
from all types of form elements. In all cases, the form is called
feedback
and the element is called field
.
Text Boxes, <textarea>s and hiddens
These are
the easiest elements to access. The code is simply
You'll
usually be checking if this value is empty, i.e.
return false;
}
That's
checking the value's equality with a null String (two single quotes with
nothing between them). When you are asking a reader for their email address,
you can use a simple » address validation function to make sure the address has a valid structure.
Select Boxes
Select
boxes are a little trickier. Each option in a drop-down box is indexed in the
array
options[]
, starting as always with 0. You then get the value of the element at this index.
It's like this:[document.feedback.field.selectedIndex].value
You can
also change the selected index through JavaScript. To set it to the first
option, execute this:
Check Boxes
Checkboxes
behave differently to other elements — their value is always
on
. Instead, you have
to check if their Boolean checked
value is true or, in
this case, false. // box is not checked
return false;
}
Naturally,
to check a box, do this
Radio Buttons
Annoyingly,
there is no simple way to check which radio button out of a group is selected —
you have to check through each element, linked with Boolean AND operators .
Usually you'll just want to check if none of them have been selected, as in this example:
!document.feedback.field[1].checked &&
!document.feedback.field[2].checked) {
// no radio button is selected
return false;
}
You can
check a radio button in the same way as a checkbox.
JavaScript Form Validation
JavaScript validation check form before submitting to server all field in form
filled properly or not. If any validation fails, it stops submitting form to
server. It returns a error message to user about failure of form submission. It
indicates error focus on form where error is found on field.
User can understand
what real problem occurred in form by seeing error on field and they fill again
proper value in field and can submit it again.
JavaScript validation
have good thing, it is executed on client side. This will save server side
process and resources of server. Server will not busy with this work of form
validation.
JavaScript validation
is much faster and instant result provide to user. This increases the
submission process to server with valuable data.
JavaScript Validation
Required Validation
Required Validation
means field should not submit empty to the server. It should contain any
record, characters numbers or special characters before submitting to the
server.
Demo
<html>
<head>
<title>Required Validation</title>
<script>
function validate()
{
var vUser=trim(document.frm.sUser.value);
var vPwd=trim(document.frm.sPwd.value);
if(vUser=="")
{
alert("User Name Field is Empty");
document.frm.sUser.focus();
return false;
}
else if(vPwd=="")
{
alert("Password Field is Empty");
document.frm.sPwd.focus();
return false;
}
}
function trim(s) {
return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}
</script>
</head>
<body>
<form name="frm" onSubmit="return validate();">
User Name <input type="text" name="sUser" /><br>
Password <input type="password" name="sPwd" /><br>
<input type="submit" name="goTo" value="Submit"/>
</form>
</body>
</html>
Number or Integer
Validation
Number Validation in
JavaScript should only contain numeric digits and contain no alpha characters
or not any special characters. This number can be 0-9. Number Validation is
used in phone number validation, currency check
or some particular requirement.
Demo
<html>
<head>
<title>Number Integer Validation</title>
<script>
function validate()
{
var dValidate=document.frm.numberValidate.value;
if(dValidate=="")
{
alert("Number Field is empty")
return false;
}
else if(isDigits(dValidate)==false)
{
alert("Field is not numeric")
return false;
}
}
function isDigits(argvalue) {
argvalue = argvalue.toString();
var validChars = "0123456789";
var startFrom = 0;
if (argvalue.substring(0, 2) == "0x") {
validChars = "0123456789abcdefABCDEF";
startFrom = 2;
} else if (argvalue.charAt(0) == "0") {
validChars = "01234567";
startFrom = 1;
}
for (var n = 0; n < argvalue.length; n++) {
if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
}
return true;
}
</script>
</head>
<body>
<form name="frm" onSubmit="return validate();">
Number <input type="text" name="numberValidate" />
<input type="submit" name="goTo" value="Number Validate" />
</form>
</body>
</html>
Date Validation
Date Validation should
used for data format. Date should either not empty or not in wrong format
before submitting to the server. Date Validation is used for late Date
submission, event start, event end, reminders date, or date of birth.
Demo
<html>
<head>
<title>Date Validation</title>
<script>
function validate()
{
var dValidate=document.frm.dateValidate.value;
if(dValidate!="")
{
var arDValidate=dValidate.split("/");
if(arDValidate.length==3)
{
if(arDValidate[0].length!=2 || (arDValidate[0]>32))
{
alert("Wrong Date format");
return false;
}
else if(arDValidate[1].length!=2 || (arDValidate[1]>13))
{
alert("Wrong Month format");
return false;
}
else if(arDValidate[2].length!=4 || (arDValidate[2]<1900))
{
alert("Wrong Year format");
return false;
}
else
{
var dateDate=new Date(arDValidate[2],arDValidate[1]-1,arDValidate[0]);
if((arDValidate[0]!=dateDate.getDate()))
{
alert("Wrong Date Enter e.g date month year is not correct 31 feb 2009");
return false;
}
}
}
else
{
alert("Wrong Format");
return false;
}
}
else
{
alert("Date is blank");
return false;
}
}
</script>
</head>
<body>
<form name="frm" onSubmit="return validate();">
mm/dd/yyyy <input type="text" name="dateValidate" />
<input type="submit" name="goTo" value="Date Validate" />
</form>
</body>
</html>
Email Validation
Email Validation is
used for checking proper email format. Email contains one dot and one @. This
should be present in any email format with some text. It also checks @ start
with some characters, and dot has some characters also.
Demo
<html>
<head>
<title>Email Validation</title>
<script>
function validate()
{
var dValidate=document.frm.emailValidate.value;
if(dValidate=="")
{
alert("Email Field is empty")
return false;
}
else if(checkEmail(dValidate)==false)
{
alert("Email Format is not correct")
return false;
}
}
function checkEmail(emailStr) {
if (emailStr.length == 0) {
return true;
}
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
var atom=validChars + "+";
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray == null) {
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
if (user.match(userPat) == null) {
return false;
}
var IPArray = domain.match(ipDomainPat);
if (IPArray != null) {
for (var i = 1; i <= 4; i++) {
if (IPArray[i] > 255) {
return false;
}
}
return true;
}
var domainArray=domain.match(domainPat);
if (domainArray == null) {
return false;
}
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if ((domArr[domArr.length-1].length < 2) ||
(domArr[domArr.length-1].length > 3)) {
return false;
}
if (len < 2) {
return false;
}
return true;
}
</script>
</head>
<body>
<form name="frm" onSubmit="return validate();">
Email <input type="text" name="emailValidate" />
<input type="submit" name="goTo" value="Email Validate" />
</form>
</body>
</html>
Alpha Character
Validation
Alpha character starts
with a to z characters with lower case and upper case. But it does not contain
any special symbol and any numeric value. This validation is used for first
name, last name country, city name and other particular propose.
Demo
<html>
<head>
<title>Alpha number Validation</title>
<script>
function validate()
{
var dValidate=document.frm.alphaValidate.value;
if(dValidate=="")
{
alert("Alpha Field is empty")
return false;
}
else if(isAlpha(dValidate)==false)
{
alert("Field is not alpha character")
return false;
}
}
function isAlpha(argvalue) {
argvalue = argvalue.toString();
var validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var n = 0; n < argvalue.length; n++) {
if (validChars.indexOf(argvalue.substring(n, n+1)) == -1)
return false;
}
return true;
}
</script>
</head>
<body>
<form name="frm" onSubmit="return validate();">
Alpha Character <input type="text" name="alphaValidate" />
<input type="submit" name="goTo" value="Alpha Validate" />
</form>
</body>
</html>
No comments:
Post a Comment