Simple form Validation for “All Emails”

Here is a simple way to validate all email inputs on a page a valid format.  You’ll want to check this with your Form’s On submit

<script>
        var OverRide = false;

        function setOverRide(){
            OverRide = true;
        }

        function isValidEmail(Value){
            var emailPattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return     emailPattern.test(Value);
        }

        function CheckEmails(){

            if (OverRide)
                return true;

            returnVal = true;
            $('.requiresEmail').each(    function () {
                if (!isValidEmail($(this).val())){
                    $(this).css('background-color', '#f1c7c4');
                    returnVal = false;
                } else
                    $(this).css('background-color', '#fff');
            });

            return returnVal;    
        }

    </script>

You’ll need to set your email inputs with the class requiresEmail

<input type="text" class="requiredEmail" name="email" id="email">

And check your form this way:

<form name="checkoutInformation" action="/destination" method="post" onsubmit="return CheckEmails();">

Clearing HTML Tags from a String Variable

How to remove HTML TAG-LIKE content from your strings…

Suppose you have content submitted from your client to the server, and you want to brute force scrub it out…  It’s simple with the following code:

  • ColdFusion In CFSCRIPT
    variables.TaglessString = REReplace(trim(variables.TaggedString),']*>','','all')
  • PHP – http://php.net/manual/en/function.strip-tags.php
    string strip_tags ( string $str [, string $allowable_tags ] )
  • Javascript / AKA JQUERY
    $('#theText').text()

Send me more web languages languages, and I’ll surely post it here.

JS form Email List Validation

Using the JQuery .each() function you can capture if a list of inputs are a proper format.  For this example, we’re checking EACH input with the class value set to requiresEmail.

$('.requiresEmail').each()

In the Each statement, you’ll call a function to perform the actual validation.  In this example, I am calling the isValidEmail function and testing the input’s value against the trust regex email validation.

	var OverRide = false;

	function setOverRide(){
		OverRide = true;
	}
	function isValidEmail(Value){
                var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
		return 	emailPattern.test(Value);
	}
	function CheckEmails(){
		if (OverRide)
			return true;

		returnVal = true;
		$('.requiresEmail').each(	
                   function () {
			if (!isValidEmail($(this).val()))
			{
				$(this).css('background-color', '#f1c7c4');
				returnVal = false;
			}
			else
				$(this).css('background-color', '#fff');
		   }
                );

		return returnVal;	
	}

The CheckEmails function should be called to execute the script, and there is a flag to override the validation.

JQuery AJAX Details

The devil is in the details, and the web is no exception. You must keep you user informed each step along the way.

In this post I consider feedback for the customer when performing a single page application call back to the server. When you request is off to the server, use the native CSS Cursor. Set it to Wait, and back to Default when the request is completed, and handled.

CSS to Manipulate the cursor appearance!

 document.body.style.cursor = 'wait'; document.body.style.cursor = 'default'; 

Determining when to change cursor appearance!

The JS Code below determines if the enter or escape key is pressed. Often these keys call for serious actions, and events. This allows you to determine the keyCode and then of course gives you the opportunity to display a good cursor.

// Define the Enter and Escape Keys var KEYCODE_ENTER = 13; var KEYCODE_ESC = 27; 
//check the key pressed, and if it matches, then display the proper cursor 

$(document).keyup(function(e) { 
 if (e.keyCode == KEYCODE_ENTER) { //Change cursor } 
 if (e.keyCode == KEYCODE_ESC) { //Change Cursor } 
}); 

 

JS FormValidation

The following is a simple collection of String Validation techniques I have commonly used in JavaScript.

Validating an email address with a simple JavaScript Function.

This is a very simple piece of code.  The function checkEmails accepts a arrayChunk with one or two email values.  Then checks if there are two emails, they match.  If they match it checks the format against the regex defined to catch email validity. Return the boolean!

		 
     /* The Function */
	 function checkEmails(arEmail) { 
	 	returnVal = true; 
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/; 
		if (arEmail.length == 2 && $('#' + arEmail[0]).val() != $('#' + arEmail[1]).val()) 
			returnVal = false; 
		else if (returnVal && !emailPattern.test($('#' + arEmail[1]).val())) 
			returnVal = false; 
		
		return returnVal; 
	} /* Call the Function */ checkEmails ( [ Val1, Val2 ] ); 

Working with Dynamic HTML Elements

With the ever expanding ability to create single page applications for the web we are constantly approaching new problems that must be handled creatively. While our tools become increasingly more capable our browsers do not. One thing that is not handled super cleanly is how jQuery binds to DOM elements or rather how jQuery doesn’t rebind when new elements are added to the DOM.

Consider a single page application that loads an Edit form for a user profile. The new edit form has fields that cannot have auto-binded events to the elements. To make this work, you cannot use the standard jQuery bindings:

 $('.UpdateEmail').keyup(function (e) { /* Perform Work */ } 

You must use the .live() function…

 $('.UpdateEmail').live('keyup', function (e) { /* Perform Work */ } 

The new code is rather simple, move the keyup event handler to the the first paramerter of live, and perform the same work as a second parameter.