Custom Input Checking

Example 1

In this example, we use JavaScript to write validate the expiry date in a field. We also convert the postal code to all caps

Code:

in head

<script>
function fixPC(){
	var els = document.getElementsByName("PC");
	var text = els[0].value.trim();
	text = text.toUpperCase();
	els[0].value = text;
}
</script>

in external js file:

<script>
function checkForm(){  
	var el = document.getElementById("expiration_date");
	
	if (checkExpire(el))
      outputMsg();
   	return false;
}

function checkExpire(field){  
	var arr = field.value.split("/");
   	var mm=arr[0], yy=arr[1];
   	if ( ! (1 <= mm && 12 >= mm  &&
           18 <=yy && 23 >= yy)){
   		return formErr(field, field.value);
   	}
   return true;
} 

function formErr(entry, msg){  
	alert(entry.name + ": " + msg + " is invalid.");
   	entry.focus();
   	entry.select();
   	return false;
}
function outputMsg(){
	alert("All good!");
}
</script>