Validate form in onsumbit function : onSubmit « Event onMethod « JavaScript DHTML






Validate form in onsumbit function

 


<html>
<head>
<title>Try/Catch</title>
</head>
<body>
<form name="formexample" id="formexample" action="#">
<div id="valueDiv">Enter a Number Between 1 and 100: <input id="num" name="num"></div>
<div><input id="submit" type="submit"></div>
</form>
<script type="text/javascript">
function checkValid() {
    try {
        var numField = document.forms[0]["num"];
        if (isNaN(numField.value)) {
            throw "Not a number";
        }
        if ((numField.value > 100) || (numField.value < 1)) {
            numField.style.background = "#FF0000";
            return false;
        }
        else {
            numField.style.background = "#FFFFFF";
            return true;
        }
    } catch(errorObject) {
        document.write(errorObject);
        document.write("<BR>");
    } finally {
        document.write("finally.");
    }
}
function init() {
    document.forms[0].onsubmit = function() { return checkValid() };
}
window.onload = init;
</script>
</body>
</html>

   
  








Related examples in the same category

1.'onSubmit' Example
2.onsubmit action