www.webdeveloper.com
Results 1 to 2 of 2

Thread: JavaScript Form Validation on submit

  1. #1
    Join Date
    Sep 2014
    Posts
    3

    JavaScript Form Validation on submit

    I have a simple form and am validating onchange and need a final validation onsubmit. I am displaying a message to the right of the inputbox on error.
    I'm trying to keep this at DOM 1 compatible and not use any framework.

    HTML

    Code:
    <form id = "myForm" action = "" onsubmit = "return validateForm(this);">
                    <table class = "table-submit" border = "0">
                        <tr>
                            <td>
                                Username: 
                            </td>
                            <td>
                                <input type = "text" id = "username" 
                                    size = "30" maxlength = "30"
                                    onchange = "validateUsername(this, 'msgUsername')" />
                            </td>
                            <td id = "msgUsername">
                                &nbsp;
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Password: 
                            </td>
                            <td>
                                <input type = "password" id = "password" 
                                    size = "30" maxlength = "30"
                                    onchange = "validatePassword(this, 'msgPassword')" />
                            </td>
                            <td id = "msgPassword">
                                &nbsp;
                            </td>
                        </tr>
                        <tr>
                        <td>&nbsp;</td>
                        <td>
                            &nbsp;
                            <input type = "submit" value = "Submit"  />
                            &nbsp;
                            <input type = "reset" value = "Clear" />
                        </td>
                    </tr>
                    </table>
    </form>
    JavaScript

    Code:
    function validateUsername(myItem, myElement) {
    var dom = document.getElementById(myElement);
    
        if (myItem.value.length < 3) {
            dom.innerHTML = " Username needs to be a minimum of 3 characters! ";
            return false;
        }
        else {
            dom.innerHTML = "";
            return true;
        }
    }
    
    function validatePassword(myItem, myElement) {
    var dom = document.getElementById(myElement);
    
        if (myItem.value.length < 5) {
            dom.innerHTML = " Password needs to be a minimum of 5 characters! ";
            return false;
        }
        else {
            dom.innerHTML = "";
            return true;
        }
    }
    
    function validateForm (itm) {
    
        // kind of stuck here...
    }
    As you may of noticed, I am a bit stuck on my validateForm() function. The code validates on each inputbox onchange event. Not sure what is the best way to go from here. I thought about doing an If for my both single input box validation, but I would need to send each parameters which is what i was trying to avoid by using this. Would like some suggestions.

  2. #2
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    956
    Typically I like to keep my solutions as close to the original code as possible. I feel it's easier for a user to learn when they are looking at changes to their own code, rather than brand new code. Your case was a bit tricky and frankly there were a number of ways this could have been done. Right now your validation seems to only be based around length and so my response focuses on that. However in the event you ever need a more complex validation, this code would need to be scrapped and replaced with a more fitting solution.

    Anyway, the major changes are that I combined your validateUsername() and validatePassword() functions, since they effectively did the same thing, from a functionality standpoint. The difference would be the length parameter, which could just be passed into the function as another argument. The next big change would be that I added an object to keep up with the validity of your form. Since in all reality, your validation functions were just being used to set or remove error messages for the user, I needed a way programmatically keep up with each form field's valid status. So now this length validation will also update a value, which gets used later when the form submits. If any field values are left as invalid the form will not submit.

    Code:
    	<form id="myForm" action="" onsubmit="return validateForm()">
    		<table class="table-submit" border="0">
    			<tr>
    				<td>Username: </td>
    				<td><input type="text" id="username" size="30" maxlength="30" onchange="validateLength(this, 'msgUsername', 3)" /></td>
    				<td id="msgUsername">&nbsp;</td>
    			</tr>
    			<tr>
    				<td>Password: </td>
    				<td><input type="password" id="password" size="30" maxlength="30"	onchange="validateLength(this, 'msgPassword', 5)" /></td>
    				<td id="msgPassword">&nbsp;</td>
    			</tr>
    			<tr>
    				<td>&nbsp;</td>
    				<td colspan="2">
    					&nbsp;
    					<input type="submit" value="Submit" />
    					&nbsp;
    					<input type="reset" value="Clear" />
    				</td>
    			</tr>
    		</table>
    	</form>
    	
    	<script>
    		var $validForm = {"username": "invalid", "password": "invalid"};
    		function validateLength($i, $e, $l) {
    			document.getElementById($e).innerHTML = ($i.value.length < $l) ? " Needs to be a minimum of " + $l + " characters! " : "";
    			$validForm[$i.id] =  ($i.value.length < $l) ? "invalid" : "valid";
    		}
    
    		function validateForm() {
    			for(var $i in $validForm) if($validForm[$i] == "invalid") return false;
    			return true;
    		}
    	</script>
    Also, I tend to condense my code down simply because I like the elegance that small and simple code provides. I realize these sorts of things can be easier to read and understand when written in an expanded form with brackets and if this is necessary I can do so as well as explain my code further.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles