jQuery: Form validation with keyup examples

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
	<script>
	$(document).ready(function(){

		$("#txtFirstName").keyup(function() {
		
			 $('span.error').hide();

			var firstName = $(this).val();
			// allow '.','-' and space
			var firstNameRegex =/^[A-Za-z\s\'\-]*$/; //  /^[A-Za-z\s\'\-]*$/; //^[a-z\s]*$ ==== ^[A-Za-z\s][\.]{0,1}[A-Za-z\s]{0,}$"
			
			console.log(firstName);

			if(firstNameRegex.test(firstName)) 
			{
				$(this).after('<span class="error">Valid</span>');
			} 
			else 
			{
				$(this).after('<span class="error">Wrong!</span>');
			}
		});
	

		$("#txtEmail").keyup(function() {
		
			 $('span.error').hide();

			var email = $(this).val();
			var emailRegex = /^(([^<>()[\]\\.,;:\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,}))$/;
			
			console.log(email);

			if(emailRegex.test(email)) 
			{
				$(this).after('<span class="error">Valid</span>');
			} 
			else 
			{
				$(this).after('<span class="error">Wrong!</span>');
			}
		});



		$("#btnSubmit").click(function() {

			$('span.error').hide();

			// note that toUpperCase() is used, not perfect solution
			var postalCode = ($("#txtPostalCode1").val() + $("#txtPostalCode2").val()).toUpperCase();
			var postalCodeRegex = /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/;
			var btnSubmit = $("#btnSubmit");

			console.log(postalCode);

			if(postalCodeRegex.test(postalCode)) 
			{
				$(btnSubmit).after('<span class="error">Valid</span>');
			} 
			else 
			{
				$(btnSubmit).after('<span class="error">Wrong!</span>');
			}
		});
	})
	</script>
</head>

<body>
		First name: 
		<input type="text" name="txtFirstName" id="txtFirstName" />
		<br />
		<br />
		Email: <input type="text" name="txtEmail" id="txtEmail" />
		<br />
		<br />
		Postal Code: 
		<input type="text" name="txtPostalCode1" id="txtPostalCode1" maxlength="3" style="width:30px; margin-right:10px;" />
		<input type="text" name="txtPostalCode2" id="txtPostalCode2" maxlength="3" style="width:30px; margin-right:10px;" />
		<input type="submit" value="Submit" id="btnSubmit" />
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *