JavaScript form validation

<form name="myform" onsubmit="return validateForm()">
   <!-- No space or no other tag can exist between input and img tags. -->
   <input type="text" name="FullName"/><img style="position:absolute; display:none;"   
       src="~/Assets/MyImages/FormValidationError.png" />
</form>
<script>
    function validateForm() {

        var form = document.forms["myform"];
        var fullNameTextBox = form["FullName"];            
        var fullName =fullNameTextBox.value;      
        if (fullName == null || fullName == "") {
            alert("Name must be filled out.");
            
            var errorImageElement= fullNameTextBox.nextSibling; // no space/tag allowed between input and img
            //OR, var errorImageElement= fullNameTextBox.nextElementSibling; //space(s) allowed between input                  
                                                                             and img
   
            errorImageElement.style.display = 'inline';
            //OR, errorImageElement.setAttribute('class', 'visible');
            return false;
        }

        return true;
    }

    //Code to validate file input.
    //if (document.getElementById("UploadFile").files.length == 0) {
    //    console.log("no files selected");
    //}
</script>
Advertisements

JavaScript form validation

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>

<form onsubmit="return validateForm()">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>