'Bind event with form in JavaScript

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.



Solution 1:[1]

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.

Solution 2:[2]

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.
}

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Felix Kling
Solution 2 Samuel Liew
Solution 3 Ahs N