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.
For an alternative approach to client-side form validation, without Java Script, check out our new article on HTML5 Form Validation which is available now in most modern browsers.
When form input is important, it should always be verified using a secure server-side script.
Otherwise a browser with Java Script disabled, or a hacker trying to compromise your site, can easily submit invalid data. The first test in the example is therefore only necessary in order to provide a different error message when the input is blank.
The purpose of a form validation script is to return a boolean value ('s to reference form fields, but that can lead to namespace conflicts and why make things more complicated than necessary.
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.
So i have places to insert the stop validation code, but just cant find any that works.
The value of a text input box (or a textarea or password input) is available using the syntax that tells you which option has been selected.
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.
Validating form input with Java Script is easy to do and can save a lot of unnecessary calls to the server as all processing is handled by the web browser.
It can prevent people from leaving fields blank, from entering too little or too much or from using invalid characters.