0

I am creating form using JavaScript. Like below

var form = document.createElement('form');
form.action = 'abc.com';
form.noValidate = true;
form.id = 'myForm';
form.onsubmit = 'return validateMyForm();';

I am trying to add validator that checks required fields before submit form. So I follow JavaScript to stop form submission. But it didn't attach event to the form. How can I achieve this in JavaScript ?

No JQuery please.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Junaid
  • 2,572
  • 6
  • 41
  • 77

3 Answers3

4

You have to assign a function to onsubmit, not a string:

form.onsubmit = validateMyForm;

Don't confuse DOM properties with HTML attributes. Writing something like

<form onsubmit="return foo();">

would be (roughly) equivalent to

form.onsubmit = function(event) {
    return foo();
};

when working with the DOM.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You can't put a function into a string.

form.onsubmit = function() {
  var valid = true;

  // TODO: form validation

  // Not valid, return false
  if(!valid) {
    alert('Please correct the following errors:');
    return false;
  }

  // valid, do nothing.
}
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
0

You can directly use the required attribute of HTML5 on your input like so:

<input type="text" name="lastname" required>

This will cause html5 to validate the fields before submitting. There are several other attributes that may be used for validation as well depending on the type of data you want to validate.

No need to use javascript for the validation.

Ahs N
  • 8,233
  • 1
  • 28
  • 33