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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s