The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button: The validation rules for the form above are as follows: This code adds a script tag and an alert command.And when the page loads, the Java Script code will be executed (the user will see an alert box).We will also do two more things when the user submits the form: The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again). Now, we can check each $_POST variable with the test_input() function, and the script looks like this: Notice that at the start of the script, we check whether the form has been submitted using $_SERVER["REQUEST_METHOD"].If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated.The illustration below shows this relationship: Note that the 'I' in selected Index needs to be capitalised - Java Script functions and variables are always case-sensitive. Read more about the humble checkbox in our HTML5 Checkbox Validation article.Radio buttons are implemented as if they were an array of checkboxes.It explains some of the code examples above as well as introducing more advanced concepts: We would be remiss in not pointing out that your Java Script and HTML code should be kept separated as far as possible. I've coded a working form, all checks are great but for some reason the hardest part is trying to stop form submission before validation.
Proper validation of form data is important to protect your form from hackers and spammers!
I tested your first piece of code on a form and it does not work at all.
Tried setting it up on onsubmit on both form and button and no go.
The purpose of a form validation script is to return a boolean value ( to reference form fields, but that can lead to namespace conflicts and why make things more complicated than necessary.
When the form is submitted - either by hitting Enter or clicking on the Submit button - the to abort (cancel) the form submission. In a real-life situation you will most likely have more fields to check, and more complicated conditions, but the principle remains the same.