0

I'm currently making a html web page for my course where the user inputs some data in a form which is then meant to be validated via a separate javascript file which gives an alert with the errors. This is my javascript code currently:

function init() {
  var rForm = document.getElementById('regform');
  rForm.onSubmit = validate();
}

window.onload = init;

So it's meant to get the form with the id 'regform' and then when that form is submitted, call the validation function. However as soon as the web page loads, it calls the validation function and gives the errors and when the form is submitted is does not call the function which is meant to stop the form from submitting. The validation code works as I've tested it by placing the code in the html file, but I have to put the code in a separate javascript file. So for some reason it's skipping the rForm.onSubmit and going straight to calling validate(). I am new to javascript so it may be something really obvious.

  • 1
    `rForm.onSubmit = validate();` => `rForm.onsubmit = validate;` or better `rForm.addEventListener("submit", validate);` (using something [like this](http://stackoverflow.com/questions/23799296/js-li-tag-onclick-not-working-on-ie8/23799448#23799448) if you need to support obsolete browsers like IE8, which -- sadly -- many people still do). – T.J. Crowder May 02 '17 at 14:07
  • `rForm.onsubmit = validate;` makes nothing happen. `rForm.addEventListener("submit", validate);}` calls `validate` and the error messages are shown however it seems like it can't return the value of `validate` as it submits the form anyway – John Roberts May 02 '17 at 14:20
  • *"`rForm.onsubmit = validate; makes nothing happen.`"* With respect, that will only be the case if `validate` doesn't do anything -- unless of course something else is also assigning to the `onsubmit` property elsewhere, which is why using those old DOM0-style handlers isn't a good idea. If `validate` does something and returns `false` if the validation fails, it will prevent form submission. Re `addEventListener`, `validate` needs to not just return a flag. I assumed you'd search for examples (like [this one](http://stackoverflow.com/a/40941195/157247)) and adapt it. – T.J. Crowder May 02 '17 at 14:28
  • Ok well it turns out that the problem was just that I had `rForm.onSubmit = validate;` when I should have had `rForm.onsubmit = validate;`. The capital S broke it. In my inexperience, I did not realise that javascript is very case sensitive. I'm used to working in more lenient languages and I like my CamelCase. Lesson learnt. Thanks for your help anyway – John Roberts May 02 '17 at 14:31
  • I did point that out in my first comment above; I could have flagged up there were *two* changes (case *and* parens). Glad you sorted it out. – T.J. Crowder May 02 '17 at 14:32

0 Answers0