RPeraltaJr
11/26/2018 - 5:24 AM

Form Validations with JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form method="POST" action="something.php" name="myForm" onsubmit="return validateForm()">
        <div class="form-group">
            <label for="fname">first name</label>
            <input type="text" name="first_name" id="fname">
        </div>
        <div class="form-group">
            <label for="lname">last name</label>
            <input type="text" name="last_name" id="lname">
        </div>
        <div class="form-group">
            <button type="submit" name="submit">Submit</button>
        </div>
    </form>

    <script src="form-validation.js"></script>
</body>
</html>


function validateForm() {
    var firstName = document.getElementById('fname').value;

    if( firstName == null || firstName == '' ) {
        alert("First name is required!");
        return false;
    } 

    // at least 3 characters 
    if( firstName.length < 3 ) {
        alert("First name must be at least 3 characters");
        return false;
    }
}