In this JavaScript tutorial, we will see how to perform HTML form validation using the onsubmit event. We will also see how to cancel the form submission based on validation function outcome.
24a_Javascript Tutorial – Form Validation.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!DOCTYPE html> <head> <Title> Java Script Windows </Title> </head> <body> <Script type="text/javascript"> //Sample 01: Return true or false here //Look at onclick= in the form function ValidateNumber(NumberForm) { var theNumber = NumberForm.ANumber.value; if (theNumber=="") { alert("The input Field is empty"); return false; } if (isNaN(theNumber)) { alert("That's not a valid Number"); NumberForm.ANumber.focus(); return false; } return true; } </Script> <form action="DummyAction.html" method="POST" onsubmit="return ValidateNumber(this)"> Enter a Number (Just for a Test) <input type="text" name="ANumber" value="650"/> <input type="submit" value="Submit" /> </form> </body> </html> |
24b_DummyAction.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <head> <Title> Java Script Windows </Title> </head> <body> <H1> Form submitted </H1> <h2> Means, you entered a valid number</h2> <p>In real world, the form will be submitted to a server. Not to a local html file like this! :) </p> </body> </html> |
Categories: JavaScript-Tube