MENU
Validating Form Input
RESETRUNFULL
Below, the user can proceed by clicking the ‘Proceed’ button or pressing Alt+s on Chrome. Alternatively, the user can go back to another page by clicking the ‘Go Back’ button or double-clicking on the page elsewhere. The ‘required’ attribute forces the input to conform to valid values for form submission.Returning a ‘false’ value within the ‘onsubmit’ attribute prevents the form from being submitted. Similarly, returning a ‘false’ value within the ‘onclick’ event attribute of a <button> or <a> element disables the default clicking action, which is equivalent to the calling of element.preventDefault().On the second ‘submit’ button, the ‘formnovalidate’ attribute overwrites the ‘required’ attribute, and the ‘formaction’ attribute overwrites the ‘action’ attribute on <form>.
<!DOCTYPE html><html><body><form onsubmit="return confirmAge();"
action="age_set.php">
<label for="a1" >Your age:</label>
<input id="a1" name='age' type="number" step="1"
min="0" max="100"
oninput="checkAge(this)" required/>
<input name="sbutton1" type="submit"
value="Proceed" accesskey="s" />
<input name="sbutton2" type="submit"
value="Go Back" formaction="register.html"
formnovalidate onclick="pass()"/>
</form>
<script>
function checkAge(inp){
var v = inp.value;
if (Math.round(v)==v && v>=10 && v<=100)
inp.setCustomValidity(``); // no error msg!
if (!inp.checkValidity()){
inp.setCustomValidity(
`Invalid age: ${inp.value}.`);
inp.reportValidity(); // displays the error msg
}
}
function confirmAge(){
return confirm(`Are you sure you are
${document.forms[0].age.value} years old?`);
}
function pass(){
document.forms[0].onsubmit=()=>true;
}
document.ondblclick=()=>{
let f = document.forms[0];
if (f.requestSubmit) {
pass();
f.requestSubmit(f.sbutton2);
}
else f.submit();
}
</script></body></html>