Validating form input
Form input is very important for some Web- pages. The form input is often sent back to the server again. JavaScript has got the functionality to validate the form input before sending it to the server. First I want to show you how forms can be validated. Then we will have a look at the possibilties for sending information back with JavaScript or HTML.
First of all we want to create a simple script. The HTML- page shall contain two text- elements. The user has to write his name into the first and an e-mail address into the second element. You can try this scripts in the online version of my tutorial.
Concerning the first input element you will receive an error message when not entering anything. Any input is seen as valid input. Of course, this does not prevent the user from entering any wrong name. The browser even accepts numbers. So if you enter '17' you will get 'Hi 17!'.
The second form is a little bit more sophisticated. If you try to enter a simple string - your name for example it won't work (unless you have a @ in your name...). The criteria for accepting the input as a valid e-mail address is the @. A single @ will do it - but this is certainly not very meaningful. Every Internet e-mail address contains a @ so it seems appropriate to check for a @ here.
What does the script for those two form elements and for the validating look like? Here it goes:
function test1(form) {
if (form.text1.value == "")
alert("Please enter a string!")
else {
alert("Hi "+form.text1.value+"! Form input ok!");
}
}
function test2(form) {
if (form.text2.value == "" ||
form.text2.value.indexOf('@', 0) == -1)
alert("No valid e-mail address!");
else alert("OK!");
}
// -->
No comments:
Post a Comment