Title: Client-side (JavaScript) Validation
1Client-side (JavaScript) Validation
2Associating a function with a click event Part 1
Use the input tags onclick attribute to
associate a function that we will define next
with the buttons click event. It will go to
this function and execute it before going to the
server.
3Define function associated with click, place it
in a ltscriptgt section in the ltheadgt section
4Function Code
- function validateForm()
-
- var firstNamedocument.getElementById("txtFirstNa
me").value - if(firstName "")
-
- alert("Please enter a first name.")
- return false
-
-
The name of the function here must match exactly
(case included) what appears in the buttons
onclick attribute
5Extract data from a textfield
- var firstNamedocument.getElementById("txtFirstNam
e").value - The keyword var is used by JavaScript to declare
a variable. - The getElementById method takes a string argument
which is the id attribute of the element of
interest. (Its usually in quotes.) - After the method comes a period and then the
attribute of the element you desire in this
case the value which is the content of a textbox - The content of the textbox is then assigned to
the firstName variable
6Test for value
- if(firstName "")
-
- alert("Please enter a first name.")
- return false
-
- Test condition of there being a nontrivial value
for firstName which came from the text field. - If there was nothing in the text field, pop up an
alert box infroming the user of the problem. - The return false statement prevents the page from
being sent back to the server
7Result Alert box and does not go to server
8In JavaScript else if is two words!