In order to make the default validation rule take effect, some issues should be considered:
1) for the submit button, we can use either:
<button type="submit">Submit</button>
or
<input type="submit" value="Submit">
the key point here is we should have the attribute inside: type="submit"
2) instead of using onclick, we should use onsubmit in the <form>, for instance:
<form onsubmit="aFunction()">...</form>
and then the aFunction() should be invoked when the form validation passed.
How to do the validation inside our own js function, HTML5 introduces a concept called "constraint validation" which is an algorithm browsers run when a form is submitted to determine its validity. To make this determination, the algorithm utilizes new HTML5 attributes like min, max, step, pattern, and required as well as existing attributes maxlength and type.
Another choise is validate the form using DOM API:
validity is a DOM property that will returns a validityState object which contains several boolean properties for us to use, say we have a node:
var ele = document.getElementById('someId');
Example
|
Validity
property
|
Notes
|
<input id="someId" pattern="[0-9]{4}"
value="123" />
|
ele.validity.patternMismatch
|
true if the node's value does not match its pattern attribute
|
<input id="someId" type="number"
max="2" value="1" />
|
ele.validity.rangeOverflow
|
true if the node's value is greater than its max attribute
|
<input id="someId" type="number"
min="2" value="3" />
|
ele.validity.rangeUnderflow
|
true if the node's value is less than its min attribute
|
<input id="someId"
type="email" value="abc" />
|
ele.validity.typeMismatch
|
true if an input node's value is invalid per its type attribute
|
<input id="someId" type="text" required
value=" " />
|
ele.validity.valueMissing
|
true if the node has a required attribute but has no value
|
<input id="someId" type="text" required
value="" />
|
ele.validity.valid
|
true if all of the validity conditions listed above are false
|
checkValidity()
The checkValidity method on a form element node (e.g. input, select, textarea) returns true if the element contains valid data, for instance:
if(ele.checkValidity()){
...
}
On form nodes it returns true if all of the form's children contain valid data,i.e.
if(document.forms['aForm'].checkValidity()){
...
}
In fact we do not need <form> but only a <div></div> to accommodate all the input controls, and using a <button onclick="aFun(...params)"></button>, the validation rule can be performed as below:
if(document.getElementById("firstName").validity.valueMissing){ alert('firstName is required'); return false; }else{ user.firstName = document.getElementById("firstName").value; }