Validations using .NET & JavaScript


Form validation – checking for non-empty

This has to be the most common type of form validation. You want to be sure that your visitors enter data into the HTML fields you have “required” for a valid submission. Below is the JavaScript code to perform this basic check to see if a given HTML input is empty or not.

JavaScript Code:

// If the length of the element's string is 0 then display helper message
function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}

Checking for all numbers

Working Example:

<script type='text/javascript'>
function isNumeric(elem, helperMsg){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
</script>
<form>
Numbers Only: <input type='text' id='numbers'/>
<input type='button' 
	onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')"
	value='Check Field' />
</form>

Checking for all letters

<script type='text/javascript'>
function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
</script>
<form>
Letters Only: <input type='text' id='letters'/>
<input type='button' 
	onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')"
	value='Check Field' />
</form>

Checking for numbers and letters

Working Example:

<script type='text/javascript'>
function lengthRestriction(elem, min, max){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <= max){
		return true;
	}else{
		alert("Please enter between " +min+ " and " +max+ " characters");
		elem.focus();
		return false;
	}
}
</script>
<form>
Username(6-8 characters): <input type='text' id='restrict'/>
<input type='button' 
	onclick="lengthRestriction(document.getElementById('restrict'), 6, 8)"
	value='Check Field' />
</form>

Selection made

Working Example:

<script type='text/javascript'>
function madeSelection(elem, helperMsg){
	if(elem.value == "Please Choose"){
		alert(helperMsg);
		elem.focus();
		return false;
	}else{
		return true;
	}
}
</script>
<form>
Selection: <select id='selection'>
<option>Please Choose</option>
<option>CA</option>
<option>WI</option>
<option>XX</option>
</select>
<input type='button' 
	onclick="madeSelection(document.getElementById('selection'), 'Please Choose Something')"
	value='Check Field' />
</form>

Email validation

And for our grand finale we will be showing you how to check to see if a user’s email address is valid. Every email is made up for 5 parts:

  1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores
  2. The at symbol @
  3. A combination of letters, numbers, hyphens, and/or periods
  4. A period
  5. The top level domain (com, net, org, us, gov, …)

Valid Examples:

  • bobby.jo@filltank.net
  • jack+jill@hill.com
  • the-stand@steven.king.com

Invalid Examples:

  • @deleted.net – no characters before the @
  • free!dom@bravehe.art – invalid character !
  • shoes@need_shining.com – underscores are not allowed in the domain name

    Working Example:

    <script type='text/javascript'>
    function emailValidator(elem, helperMsg){
    	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    	if(elem.value.match(emailExp)){
    		return true;
    	}else{
    		alert(helperMsg);
    		elem.focus();
    		return false;
    	}
    }
    </script>
    <form>
    Email: <input type='text' id='emailer'/>
    <input type='button' 
    	onclick="emailValidator1(document.getElementById('emailer'), 'Not a Valid Email')"
    	value='Check Field' />
    </form>

    All Validations together now..

    Below we have taken the HTML form code and the new function formValidatorand plugged in all the other form validation functions taught in this lesson that are referenced in formValidator.

    HTML & JavaScript Code:

    <script type='text/javascript'>
    
    function formValidator(){
    	// Make quick references to our fields
    	var firstname = document.getElementById('firstname');
    	var addr = document.getElementById('addr');
    	var zip = document.getElementById('zip');
    	var state = document.getElementById('state');
    	var username = document.getElementById('username');
    	var email = document.getElementById('email');
    
    	// Check each input in the order that it appears in the form!
    	if(isAlphabet(firstname, "Please enter only letters for your name")){
    		if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
    			if(isNumeric(zip, "Please enter a valid zip code")){
    				if(madeSelection(state, "Please Choose a State")){
    					if(lengthRestriction(username, 6, 8)){
    						if(emailValidator(email, "Please enter a valid email address")){
    							return true;
    						}
    					}
    				}
    			}
    		}
    	}
    
    	return false;
    
    }
    
    function notEmpty(elem, helperMsg){
    	if(elem.value.length == 0){
    		alert(helperMsg);
    		elem.focus(); // set the focus to this input
    		return false;
    	}
    	return true;
    }
    
    function isNumeric(elem, helperMsg){
    	var numericExpression = /^[0-9]+$/;
    	if(elem.value.match(numericExpression)){
    		return true;
    	}else{
    		alert(helperMsg);
    		elem.focus();
    		return false;
    	}
    }
    
    function isAlphabet(elem, helperMsg){
    	var alphaExp = /^[a-zA-Z]+$/;
    	if(elem.value.match(alphaExp)){
    		return true;
    	}else{
    		alert(helperMsg);
    		elem.focus();
    		return false;
    	}
    }
    
    function isAlphanumeric(elem, helperMsg){
    	var alphaExp = /^[0-9a-zA-Z]+$/;
    	if(elem.value.match(alphaExp)){
    		return true;
    	}else{
    		alert(helperMsg);
    		elem.focus();
    		return false;
    	}
    }
    
    function lengthRestriction(elem, min, max){
    	var uInput = elem.value;
    	if(uInput.length >= min && uInput.length <= max){
    		return true;
    	}else{
    		alert("Please enter between " +min+ " and " +max+ " characters");
    		elem.focus();
    		return false;
    	}
    }
    
    function madeSelection(elem, helperMsg){
    	if(elem.value == "Please Choose"){
    		alert(helperMsg);
    		elem.focus();
    		return false;
    	}else{
    		return true;
    	}
    }
    
    function emailValidator(elem, helperMsg){
    	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    	if(elem.value.match(emailExp)){
    		return true;
    	}else{
    		alert(helperMsg);
    		elem.focus();
    		return false;
    	}
    }
    </script>
    
    <form onsubmit='return formValidator()' >
    First Name: <input type='text' id='firstname' /><br />
    Address: <input type='text' id='addr' /><br />
    Zip Code: <input type='text' id='zip' /><br />
    State: <select id='state'>
    	<option>Please Choose</option>
    	<option>AL</option>
    	<option>CA</option>
    	<option>TX</option>
    	<option>WI</option>
    </select><br />
    Username(6-8 characters): <input type='text' id='username' /><br />
    Email: <input type='text' id='email' /><br />
    <input type='submit' value='Check Form' />
    </form>

    Validations in .NET

    RequiredFieldValidator::

    <asp:RequiredFieldValidator>

    Checks that the validated control contains a value. It cannot be empty. Can be used in conjunction with other validators on a control to trap empty values. Simply, we can use it to check if the input control has any value. The most important property in the RequiredFieldValidator is InitialValue.

    <asp:RequiredFieldValidator id="validTxtName runat="server" 
    controlToValidate="txtName" 
    errorMessage="Name must be entered" display="static">
    </asp:RequiredFieldValidator>

    RegularExpressionValidator:

    <asp:RegularExpressionValidator>

    Checks the value against a regular expression (pattern). Checks that the value in the control matches a specified regular expression. If the validated control is empty, no validation takes place. The most important property in theRegularExpressionValidator is ValidationExpression.

    <asp:RegularExpressionValidator id="regvH" 
    runat="server" display="static" controlToValidate="txtH" 
    errorMessage="Hours must be 1-3 digits only" 
    validationExpression="\d{1,3}"> 
    
    </asp:RegularExpressionValidator>
    CompareValidator:

    <asp:CompareValidator>

    Checks if the value is acceptable compared to a given value or compared to the content of another control. In other words, it checks that the value in the validated control matches the value in another control or a specific value. The data type and comparison operation can be specified. If the validated control is empty, no validation takes place. The most important properties in the CompareValidator are ValueToCompareControlToCompare,Operator, and type.

    <asp:CompareValidator id="comvR" runat="server" display="static"
     controlToValidate="txtR" errorMessage="Rate must be numeric"
     type="Double" operator="DataTypeCheck"></asp:CompareValidator>

    RangeValidator:

    <asp:RangeValidator>

    Checks if the input control’s value is within a specified range. In other words, it checks that the value in the validated control is within the specified text or numeric range. If the validated control is empty, no validation takes place. The most important properties in the RangeValidator are MaximumValueMinimumValue, and type.

    <asp:RangeValidator id="ranvDependents" runat="server"
     display="static" controlToValidate="txtDependents"
     errorMessage="Must be from 0 to 10"
     type="Integer" minimumValue=0 maximumValue=10>
    </asp:RangeValidator>

    CustomValidator:

    <asp:CustomValidator>

    Allows you to develop custom validation. Performs user-defined validation on an input control using a specified function (client-side, server-side, or both). If the validated control is empty, no validation takes place. The most important property in the CustomValidator is ClientValidationFunction.

    <asp:CustomValidator id="cusvDeptNum" runat="server" 
     display="static" controlToValidate="txtDeptNum"
     onServerValidate="validateDeptNum"
     errorMessage="Must be in multiples of 10" >
    </asp:CustomValidator>

    Examples In VBScript

    Sub validateDeptNum(source As Object, s as ServerValidateEventArgs) If (CInt(s.Value) Mod 10)=0 Then s.IsValid= True Else s.IsValid=False End If End Sub

    Examples In JavaScript

    function validateLength(oSrc, args)
    {
        args.IsValid = (args.Value.length >= 10);
    }

    ValidationSummary:

    <asp:ValidationSummary>

    Displays a summary of all current validation errors. In other words, reports a summary of all errors. The most important properties in the ValidationSummary are DisplayModeShowHeaderTextShowMessageBox, andShowSummary.

    <asp:ValidationSummary id=”valSummary” runat=”server” headerText=”Please correct the following errors” display=”static” showSummary= “True” />
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