views:

88

answers:

4

If I am defining a function in JavaScript at the top of my page that validates if the string entered in a form is (A-Z,a-z, or 0-9). And then I call that function when they submit it saying :

onsubmit="return Validator(this);"

If the function name is :

function Validator(form)

Why isn't it actually validating the string submitted when we actually click on submit, and is there a better way of validating forms?

+2  A: 

Almost certainly because the Validator function is not written correctly… but since you haven't shown us what it looks like, we can't say specifically why.

Perhaps it is expecting a String and you are giving it an HTMLFormElement.

David Dorward
A: 

You aren't submitting a string to Validator, you are submitting an input element. So you would do if(form.element.value != "") ... or something... And yes there is a better way

Byron Whitlock
No, input elements don't have submit events. It has to be a form.
David Dorward
Absolutely right. Brainfart ;)
Byron Whitlock
+1  A: 

An onsubmit handler function needs to return false to cancel the event (form submission) if you want to not submit and show a validation error message instead.

Plain Javascript approaches:
http://stackoverflow.com/questions/967483/form-is-still-submitted-even-though-listener-function-returns-false

jQuery approaches:
http://stackoverflow.com/questions/665470/how-to-not-submit-a-form-if-validation-is-false

micahwittman
+1  A: 

Lots of options for form validation. Depending on your framework, you may want to use Jquery's validation. If you go with yui, I have submitted a form validator that will be useful

Here is the gallery submission, from thee you can look at examples

Zoidberg