SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    validate my validation javascript!

    I have been developing a generic validation javascript, which is fully scallable to allow for different validation types to be added.Please could one of you pros take a look and see if there is anywhere i could improve, or any potential probs (browsers compatibility etc) - cheers

    The code is run by putting the following in the <form> tag:

    Code:
    onsubmit="return validate('txtField(friendly name),1,dt,..........');"
    The txtField is the name of the form field to validate, with a friendly name for alerting errors in brackets (optional). The number is to check for:

    1. required
    2. required, not all caps
    3. not all caps

    further number can be added to check other things if required (such as is a number).

    the last bit is the type of validation. The include code is:

    Code:
    function validate(valstr){
    	errors=""
    	var valArray = valstr.split(",");
    	for(i=0; i<(valArray.length-2); i=i+3){
    		if (valArray[i].indexOf("(")==-1){
    			formObj=eval("document.getElementById('"+valArray[i]+"').value");
    			valStr(valArray[i], formObj, valArray[i+1], valArray[i+2]);
    		}else{
    			formObj=eval("document.getElementById('" + valArray[i].substring(0, valArray[i].indexOf("(")) + "').value");
    			fieldName=valArray[i].substring(valArray[i].indexOf("(")+1, valArray[i].indexOf(")"));
    			valStr(fieldName, formObj, valArray[i+1], valArray[i+2]);
    		}
    	}
    	if (errors!=''){
    		alert(errors)
    		return false;	
    	}else{
    		return true;
    	};
    	
    }
    function valStr(label, str, req, type){ //string, required (0 or 1), type (em(email), pc(post code), dt(date), na(n/a))
    	if(req==1 && str==''){//validate str for something
    		errors=errors+label+' field is required\n';
    		return;
    	}
    	if(req==2){//validate str for something and not all caps
    		if(str==''){
    			errors=errors+label+' field is required\n';
    		}else if(str==str.toUpperCase()){
    			errors=errors+label+' field must not contain all capitals\n';
    		}
    		return;
    	}
    	if(req==3 && str!='' && str==str.toUpperCase()){//validate not all caps
    		errors=errors+label+' field must not contain all capitals\n';
    		return;
    	}
    	if(type=='na'){
    		return;
    	}
    	if(type=='em'){//email
    		var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|m useum))$/
    		if(!regex.test(str)){
    			errors=errors+label+' address is not typed correctly\n';
    			return;
    		}
    	}
    	if(type=='pc'){//postcode
    		var regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/
    		if(!regex.test(str)){
    			errors=errors+label+' is not typed correctly\n';
    			return;
    		}
    	}
    	if(type=='dt'){//validate date dd/mm/yyyy
    		//if(!str.match(/[0-3]{1}\d{1}\/[01]{1}\d{1}\/[12]{1}[09]{1}\d{2}/)){
    		if(!str.match(/\d{2}\/\d{2}\/\d{4}/)){
    			errors=errors+label+' must be in the format dd/mm/yyyy\n';
    			return;
    		}//ther checks it is a valid date (inc. leap year)
    		dstr=str.split('/');
    		dte=new Date(dstr[1]+'/'+dstr[0]+'/'+dstr[2]); 
    		mStr=''+(dte.getMonth()+1); 
    		mStr=(mStr<10)?'0'+mStr:mStr; 
    		if(mStr!=dstr[1]||isNaN(dte)){ 
    			errors=errors+label+' is not valid\n';  
    			return;
    		}  
    	}
    	if(type=='yr'){//validate rear range yyyy/yy
    		//if(!str.match(/[0-3]{1}\d{1}\/[01]{1}\d{1}\/[12]{1}[09]{1}\d{2}/)){
    		if(!str.match(/\d{4}\/\d{2}/)){
    			errors=errors+label+' must be in the format yyyy/yy\n';
    			return;
    		}  
    	}
    	if(type=='tm'){//validate time hh:mm
    		var regex= /^([01]?[0-9]|[2][0-3])(:[0-5][0-9])?$/
    		if(!regex.test(str)){
    			errors=errors+label+' must be in the format hh:mm\n';
    			return;
    		}
    	}
    	if(type=='pw'){//validate password, min 8 characters including 1 number and 1 capital
    		var regex=/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,}/
    		if(!regex.test(str)){
    			errors=errors+label+' must be in the format stated\n';
    			return;
    		}
    	}
    	
    	//  -- COPY THE BELOW CODE AND UN-COMMENT TO ADD NEW VALIDATION
    	
    	//if(type=='??'){
    	//  validate stuff
    	//	errors=errors+label+' must be in the format ????????\n';
    	//	return;
    	//}
    	
    	return;
    }

    monkey
    monkey - the rest is history

  2. #2
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, where to start?

    First - if you're passing in multiple arguments that are meant to be processed together, why don't you pass them in as arrays, rather than iterating in jumps?
    Code:
    onsubmit="return validate('{txtField(friendly name),1,dt},{}');"
    Then you can just iterate through the arguments, treating each one as an array of data to be processed. Makes more sense to me, anyway.

    Second - don't use eval! This:
    Code:
    formObj=eval("document.getElementById('"+valArray[i]+"').value");
    could just as easily be written like this:
    Code:
    formObj = document.getElementById(valArray[i]).value;
    Last, use switch() instead of repeating if statements.

  3. #3
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ahh - I hadn't though of using a case statement! and I will give the array a go - I gather them is some easy way to do this to do with the {}?

    monkey
    monkey - the rest is history

  4. #4
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i have changed to using a switch, but something has gone wrong! For some reason, the wrong case is being executed. Is it ok to have nested if statements in a case? Here is the new valstr function:

    Code:
    function valStr(label, str, req, type){ //string, required (0 or 1), type (em(email), pc(post code), dt(date), na(n/a))
    	if(req==1 && str==''){//validate str for something
    		errors=errors+label+' field is required\n';
    		return;
    	}
    	if(req==2){//validate str for something and not all caps
    		if(str==''){
    			errors=errors+label+' field is required\n';
    		}else if(str==str.toUpperCase()){
    			errors=errors+label+' field must not contain all capitals\n';
    		}
    		return;
    	}
    	if(req==3 && str!='' && str==str.toUpperCase()){//validate not all caps
    		errors=errors+label+' field must not contain all capitals\n';
    		return;
    	}
    	switch(type){	
    		case 'na':
    			break;
    		case 'em': //email
    			var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|m useum))$/
    			if(!regex.test(str)){
    				errors=errors+label+' address is not typed correctly\n';
    				break;
    			};
    		case 'pc': //postcode
    			var regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/
    			if(!regex.test(str)){
    				errors=errors+label+' is not typed correctly\n';
    				break;
    			};
    		case 'dt': //validate date dd/mm/yyyy
    			//if(!str.match(/[0-3]{1}\d{1}\/[01]{1}\d{1}\/[12]{1}[09]{1}\d{2}/)){
    			if(!str.match(/\d{2}\/\d{2}\/\d{4}/)){
    				errors=errors+label+' must be in the format dd/mm/yyyy\n';
    				break;
    			};//then checks it is a valid date (inc. leap year)
    			dstr=str.split('/');
    			dte=new Date(dstr[1]+'/'+dstr[0]+'/'+dstr[2]); 
    			mStr=''+(dte.getMonth()+1); 
    			mStr=(mStr<10)?'0'+mStr:mStr; 
    			if(mStr!=dstr[1]||isNaN(dte)){ 
    				errors=errors+label+' is not valid\n';  
    				break;
    			};  
    		alert(type)
    		case 'yr': //validate rear range yyyy/yy
    			alert("hello")
    			if(!str.match(/\d{4}\/\d{2}/)){
    				errors=errors+label+' must be in the format yyyy/yy\n';
    				break;
    			};  
    		case 'tm': //validate time hh:mm
    			var regex= /^([01]?[0-9]|[2][0-3])(:[0-5][0-9])?$/
    			if(!regex.test(str)){
    				errors=errors+label+' must be in the format hh:mm\n';
    				break;
    			};
    		case 'pw': //validate password, min 8 characters including 1 number and 1 capital
    			var regex=/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,}/
    			if(!regex.test(str)){
    				errors=errors+label+' must be in the format stated\n';
    				break;
    			};
    		default:
    			break;
    	}
    	return;
    }
    I am checking a date (dt) which is valid but it keeps coming up with the yr error (hence the 2 alerts) - what have i done wrong?

    cheers
    monkey - the rest is history

  5. #5
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    any help?
    monkey - the rest is history

  6. #6
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is it ok to have nested if statements in a case?
    Gee whiz, how hard is that to test?
    Code:
    var str = "hello";
    switch(str)
    {
    	case "goodbye":
    		if(true)
    		{
    			if(true)
    			{
    				alert("goodbye case");
    			}
    		}
    		break;
    	
    	case "hello":
    		if(true)
    		{
    			if(true)
    			{
    				alert("hello case");
    			}
    		}
    		break;
    	
    	default:
    		alert("default case");
    }

  7. #7
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by 7stud View Post
    Gee whiz, how hard is that to test?
    Code:
    var str = "hello";
    switch(str)
    {
    	case "goodbye":
    		if(true)
    		{
    			if(true)
    			{
    				alert("goodbye case");
    			}
    		}
    		break;
    	
    	case "hello":
    		if(true)
    		{
    			if(true)
    			{
    				alert("hello case");
    			}
    		}
    		break;
    	
    	default:
    		alert("default case");
    }
    brilliant! does it solve my problem? - no!
    monkey - the rest is history


Bookmarks

Posting Permissions

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