Input Text value Property - Form validation: - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Input Text

Description

Input Text value Property - Form validation:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<form action="#" onsubmit="return myFunction()">
  Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
  Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
  E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
  <input type="submit" value="Submit">
</form>// w w w .ja  v a  2s .  c om

<script>
function myFunction() {
    var at = document.getElementById("email").value.indexOf("@");
    var age = document.getElementById("age").value;
    var fname = document.getElementById("fname").value;
    submitOK = "true";

    if (fname.length > 10) {
        console.log("The name may have no more than 10 characters");
        submitOK = "false";
    }

    if (isNaN(age) || age < 1 || age > 100) {
        console.log("The age must be a number between 1 and 100");
        submitOK = "false";
    }

    if (at == -1) {
        console.log("Not a valid e-mail!");
        submitOK = "false";
    }

    if (submitOK == "false") {
        return false;
    }
}
</script>

</body>
</html>

Related Tutorials