var MONTH_NAMES = new Array( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); function LZ(x) { return(x < 0 || x > 9 ? "" : "0" ) + x } function formatDate(date, format) { format = format+""; var result = ""; var i_format = 0; var c = ""; var token = ""; var y = date.getYear()+""; var M = date.getMonth()+1; var d = date.getDate(); var H = date.getHours(); var m = date.getMinutes(); var s = date.getSeconds(); var yyyy, yy, MMM, MM, dd, hh, h, mm, ss, ampm, HH, H, KK, K, kk, k; // Convert real date parts into formatted versions var value = new Object(); if (y.length < 4) {y = ""+(y-0+1900);} value["y"] = ""+y; value["yyyy"] = y; value["yy"] = y.substring(2, 4); value["M"] = M; value["MM"] = LZ(M); value["MMM"] = MONTH_NAMES[M-1]; value["d"] = d; value["dd"] = LZ(d); value["H"] = H; value["HH"] = LZ(H); if (H == 0) { value["h"] = 12; } else if (H>12) { value["h"] = H-12; } else { value["h"] = H; } value["hh"] = LZ(value["h"]); if (H>11) { value["K"] = H-12; } else { value["K"] = H; } value["k"] = H+1; value["KK"] = LZ(value["K"]); value["kk"] = LZ(value["k"]); if (H > 11) { value["a"] = "PM"; } else { value["a"] = "AM"; } value["m"] = m; value["mm"] = LZ(m); value["s"] = s; value["ss"] = LZ(s); while (i_format < format.length) { c = format.charAt(i_format); token = ""; while ((format.charAt(i_format) == c) && (i_format < format.length)) { token += format.charAt(i_format++); } if (value[token] != null) { result = result + value[token]; } else { result = result + token; } } return result; } function getDaysInMonth(month, year) { if(month == 2) if((year % 4) == 0) if((year % 100) == 0) if((year % 400) == 0) return 29; else return 28; else return 29; else return 28; else if(month == 4 || month == 6 || month == 9 || month == 11) return 30; return 31; } function trim(strText) { if(strText == null) return null; var str = strText; while (str.charAt(0) == ' ') str = str.substring(1); while (str.charAt(str.length - 1) == ' ') str = str.substring(0, str.length - 1); return str; } var cCode0 = "0".charCodeAt(0); var cCode9 = "9".charCodeAt(0); var cCodeBA = "A".charCodeAt(0); var cCodeBZ = "Z".charCodeAt(0); var cCodeLA = "a".charCodeAt(0); var cCodeLZ = "z".charCodeAt(0); function isDigit(c) { if (c == null || c.length < 1) return false; var a = c.charCodeAt(0); return (a >= cCode0 && a <= cCode9); } /////////////////////////////////////////////////////// // Validation library var validators; function initValidators() { validators = new Array(); } initValidators(); function addValidator(validator) { validators[validators.length] = validator; return validator; } function addValidatorOnFieldExists(validator) { if (validator.field != null) validators[validators.length] = validator; return validator; } function validateAll() { var nErrorCount = 0; var sErrorMessage = ""; var firstValidator = null; for(var i = 0;i < validators.length;++i) { if(!validators[i].doValidate()) { ++nErrorCount; if (nErrorCount <= 10) { sErrorMessage += "\t" + validators[i].errorMessage + "\n"; } if(firstValidator == null) firstValidator = validators[i]; } if(validators[i].stopValidation) break; } if(nErrorCount > 0) { if (nErrorCount > 10) { sErrorMessage += "\t...\n"; } if (nErrorCount == 1) alert("There was 1 error in this form, please correct it and try again:\n" + sErrorMessage) else alert(nErrorCount + " errors were found in this form, please correct them and try again:\n" + sErrorMessage) if(firstValidator != null && firstValidator.field != null) { firstValidator.field.focus(); if (firstValidator.field.select != null) firstValidator.field.select(); } return false; } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Text Validator // function validateText() { this.field.value = trim( this.field.value ); var fieldValue = this.field.value; if (!this.canBeEmpty && fieldValue.length == 0) { this.errorMessage = this.humanReadableName + " can NOT be Empty."; return false; } if (fieldValue.length == 0) { // it can be empty and it is, it is valid return true; } if (!this.canHaveAlpha || !this.canHaveNumeric || !this.canHaveSpecial || !this.canHaveSpaces) { var hasAlpha=false; var hasNumeric=false; var hasSpecial=false; var hasSpaces=false; var c; for (var i=0; i < fieldValue.length; i++) //> { c = fieldValue.charAt(i); if(isDigit(c)) { hasNumeric = true; } else if(isAlpha(c)) { hasAlpha = true; } else if (isSpace(c)) { hasSpaces = true; } else { hasSpecial = true; } } if (!this.canHaveAlpha && hasAlpha) { this.errorMessage = this.humanReadableName + " can NOT have Letters."; return false; } if (!this.canHaveNumeric && hasNumeric) { this.errorMessage = this.humanReadableName + " can NOT have Numbers."; return false; } if (!this.canHaveSpaces && hasSpaces) { this.errorMessage = this.humanReadableName + " can NOT have Spaces."; return false; } if (!this.canHaveSpecial && hasSpecial) { this.errorMessage = this.humanReadableName + " can NOT have Special Characters."; return false; } } if (fieldValue.length < this.minLen || fieldValue.length > this.maxLen) { if (this.minLen == this.maxLen) this.errorMessage = this.humanReadableName + " length must be " + this.minLen + " characters long."; else this.errorMessage = this.humanReadableName + " length must be between " + this.minLen + " and " + this.maxLen + " characters long."; return false; } return true; } function TextValidator( field, humanReadableName, validatorKeys, minLen, maxLen ) { //set up functions this.doValidate = validateText; //set up validation parameters this.validatorKeys = validatorKeys.toUpperCase(); this.canBeEmpty = this.validatorKeys.indexOf( "E" ) >= 0; this.canHaveAlpha = this.validatorKeys.indexOf( "A" ) >= 0; this.canHaveNumeric = this.validatorKeys.indexOf( "N" ) >= 0; this.canHaveSpecial = this.validatorKeys.indexOf( "L" ) >= 0; this.canHaveSpaces = this.validatorKeys.indexOf( "S" ) >= 0; this.minLen = minLen; this.maxLen = maxLen; this.field = field; this.stopValidation = false; this.humanReadableName = humanReadableName; this.errorMessage = ""; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Numeric validator // function validateNumeric() { var value = trim(this.field.value); if(value.length == 0) //this is valid ('required' is a different validator!) { return true; } var objRegExp = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; //check for numeric characters if(!objRegExp.test(this.field.value)) { this.errorMessage = this.humanReadableName + " must be a number"; return false; } if(this.min && this.field.value < this.min) { this.errorMessage = this.humanReadableName + " must be larger than " + this.min; return false; } if(this.max && this.field.value > this.max) { this.errorMessage = this.humanReadableName + " must be smaller than " + this.max; return false; } return true; } function NumericValidator(field, humanReadableName, min, max) { this.doValidate = validateNumeric; this.stopValidation = false; this.field = field; this.humanReadableName = humanReadableName; this.min = min; this.max = max; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Text Required Validator // function validateTextRequired() { if(trim(this.field.value).length == 0) { this.errorMessage = this.field.name + " is required."; return false; } return true; } function TextRequiredValidator(field, humanReadableName) { this.doValidate = validateTextRequired; this.stopValidation = false; this.field = field; this.humanReadableName = humanReadableName; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Email Validator // function validateEmail() { var emailStr = trim(this.field.value); if(emailStr.length == 0) //this is valid ('required' is a different validator!) { return true; } /* The following pattern is used to check if the entered e-mail address fits the user@domain format. It also is used to separate the username from the domain. */ var emailPat=/^(.+)@(.+)$/ /* The following string represents the pattern for matching all special characters. We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */ var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" /* The following string represents the range of characters allowed in a username or domainname. It really states which chars aren't allowed. */ var validChars="\[^\\s" + specialChars + "\]" /* The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes). E.g. "jiminy cricket"@disney.com is a legal e-mail address. */ var quotedUser="(\"[^\"]*\")" /* The following pattern applies for domains that are IP addresses, rather than symbolic names. E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */ var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/ /* The following string represents an atom (basically a series of non-special characters.) */ var atom=validChars + '+' /* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */ var word="(" + atom + "|" + quotedUser + ")" // The following pattern describes the structure of the user var userPat=new RegExp("^" + word + "(\\." + word + ")*$") /* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */ var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$") /* Finally, let's start trying to figure out if the supplied address is valid. */ /* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */ var matchArray=emailStr.match(emailPat) if (matchArray==null) { /* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */ this.errorMessage = this.humanReadableName + " does not seem to be a valid email address (check @ and .'s)"; return false; } var user=matchArray[1] var domain=matchArray[2] // See if "user" is valid if (user.match(userPat)==null) { // user is not valid this.errorMessage = this.humanReadableName + " does not seem to be a valid email (The username doesn't seem to be valid.)"; return false } /* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */ var IPArray=domain.match(ipDomainPat) if (IPArray!=null) { // this is an IP address for (var i=1;i<=4;i++) { if (IPArray[i]>255) { this.errorMessage = this.humanReadableName + " does not seem to be a valid email (Destination IP address is invalid)"; return false; } } return true } // Domain is symbolic name var domainArray=domain.match(domainPat) if (domainArray==null) { this.errorMessage = this.humanReadableName + " does not seem to be a valid email (The domain name doesn't seem to be valid.)"; return false } /* domain name seems valid, but now make sure that it ends in a three-letter word (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */ /* Now we need to break up the domain to get a count of how many atoms it consists of. */ var atomPat=new RegExp(atom,"g") var domArr=domain.match(atomPat) var len=domArr.length if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) { // the address must end in a two letter or three letter word. this.errorMessage = this.humanReadableName + "' does not seem to be a valid email (The address must end in a three-letter domain, or two letter country)."; return false; } // Make sure there's a host name preceding the domain. if (len<2) { this.errorMessage = this.humanReadableName + " does not seem to be a valid email (This address is missing a hostname)"; return false; } // If we've gotten this far, everything's valid! return true; } function EmailValidator(field, humanReadableName) { this.doValidate = validateEmail; this.stopValidation = false; this.field = field; this.humanReadableName = humanReadableName; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Date Validator // function validateDate() { this.field.value = trim( this.field.value ); var fieldValue = this.field.value; if(fieldValue.length == 0) { //empty fields are ok regardless, since they are taken care of by the required validator return true; } if (fieldValue.length == 0) { // it can be empty and it is, it is valid return true; } // get month, day, year var c, i, pos=0, month="", day="", year=""; for(i = 0; i < fieldValue.length; i++) { c = fieldValue.charAt(i); if (isDigit(c)) { switch(pos) { case 0: month += c; break; case 1: day += c; break; case 2: year += c; break; } } else pos++; } // alert( "(" + month + "/" + day + "/" + year + ")" ); if (year.length == 0 || pos > 2) { this.errorMessage = this.humanReadableName + " is an incorrectly formatted Date."; return false; } // check month if (month < 1 || month > 12) { this.errorMessage = this.humanReadableName + " has an invalid Month."; return false; } // check year if (year>=0 && year <= 49) year = (year*1) + 2000; else if (year>=50 && year<=99) year = (year*1) + 1900; if (year<1800 || year>3000) { this.errorMessage = this.humanReadableName + " has an invalid Year."; return false; } // check day if (day < 1 || day > getDaysInMonth(month, year)) { this.errorMessage = this.humanReadableName + " has an invalid Day."; return false; } var strDate = month + "/" + day + "/" + year; var theDate = new Date(strDate); // Check that the date is within the desired range var minDate = new Date(this.minDate); var maxDate = new Date(this.maxDate); if(maxDate < minDate) { //swap the minimum and maximum date if they're set wrong. var tempDate = minDate; minDate = maxDate; maxDate = tempDate; } if(theDate < minDate) { this.errorMessage = this.humanReadableName + " must be after " + this.minDate + "."; return false; } if(theDate > maxDate) { this.errorMessage = this.humanReadableName + " must be before " + this.minDate + "."; return false; } // set the field value to the calculated year this.field.value = formatDate(theDate, "MM/dd/yyyy"); return true; } function DateValidator(field, humanReadableName, minDate, maxDate) { //set up functions this.doValidate = validateDate; //set up validation parameters this.field = field; this.minDate = minDate; this.maxDate = maxDate; this.stopValidation = false; this.humanReadableName = humanReadableName; this.errorMessage = ""; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // DateRange Validator // function validateDateRange() { if(trim(this.fieldFrom.value) == "") return true; if(trim(this.fieldTo.value) == "") return true; var dateFrom = new Date(this.fieldFrom.value); var dateTo = new Date(this.fieldTo .value); if(dateTo < dateFrom) { this.errorMessage = this.humanReadableNameFrom + " must occur before " + this.humanReadableNameTo + "."; return false; } return true; } function DateRangeValidator(fieldFrom, fieldTo, humanReadableNameFrom, humanReadableNameTo) { //set up functions this.doValidate = validateDateRange; //set up validation parameters this.fieldFrom = fieldFrom; this.fieldTo = fieldTo; this.humanReadableNameFrom = humanReadableNameFrom; this.humanReadableNameTo = humanReadableNameTo; this.stopValidation = false; this.field = fieldFrom; //for setting the focus this.errorMessage = ""; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // BothFieldsRequired Validator // function validateBothFieldsRequired() { if(trim(this.field1.value) == "" && trim(this.field1.value) == "") return true; if(trim(this.field1.value) == "") { this.errorMessage = "if you enter '" + this.humanReadableName2 + "' you must also enter '" + this.humanReadableName1 + "'."; this.field = this.field1; //so that validateAll can set the focus return false; } if(trim(this.field2.value) == "") { this.errorMessage = "if you enter '" + this.humanReadableName1 + "' you must also enter '" + this.humanReadableName2 + "'."; this.field = this.field2; //so that validateAll can set the focus return false; } return true; } function BothFieldsRequiredValidator(field1, field2, humanReadableName1, humanReadableName2) { //set up functions this.doValidate = validateBothFieldsRequired; //set up validation parameters this.field1 = field1; this.field2 = field2; this.humanReadableName1 = humanReadableName1; this.humanReadableName2 = humanReadableName2; this.errorMessage = ""; this.stopValidation = false; this.field = field1; //for setting the focus return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Date Range within Validator // var ONE_DAY = 1000 * 60 * 60 * 24; function validateDateRangeWithin() { if(trim(this.fieldFrom.value) == "") return true; if(trim(this.fieldTo.value) == "") return true; var dateFrom = new Date(this.fieldFrom.value); var dateTo = new Date(this.fieldTo.value); // Convert to days var difference_days = Math.round(Math.abs(dateFrom.getTime() - dateTo.getTime()) / ONE_DAY) if(difference_days > this.daysWithin) { this.errorMessage = this.humanReadableName + ": date range must be less than " + this.daysWithin + " days."; return false; } return true; } function DateRangeWithinValidator(fieldFrom, fieldTo, humanReadableName, daysWithin) { //set up functions this.doValidate = validateDateRangeWithin; //set up validation parameters this.fieldFrom = fieldFrom; this.fieldTo = fieldTo; this.humanReadableName = humanReadableName; this.daysWithin = daysWithin; this.errorMessage = ""; this.stopValidation = false; this.field = null; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Wildcard validator function validateWildcard() { var fieldValue = this.field.value; if(fieldValue.length == 0) { //empty fields are ok regardless, since they are taken care of by the required validator return true; } if (!this.canBeEmpty && fieldValue.length == 0) { this.errorMessage = this.humanReadableName + ": The field can NOT be Empty."; return false; } if (fieldValue.length == 0) { // it can be empty and it is, it is valid return true; } var indexOfWildcard = fieldValue.indexOf("*"); if(indexOfWildcard == -1) { return true; } if(this.mustBeAtEnd && indexOfWildcard != (fieldValue.length - 1)) { this.errorMessage = this.humanReadableName + ": Wildcard characters can only be at the end."; return false; } if(this.minChars != null && fieldValue.length < (this.minChars + 1)) { this.errorMessage = this.humanReadableName + ": If you want to use wildcards, you must enter at least " + this.minChars + " characters."; return false; } return true; } function WildcardValidator(field, humanReadableName, minChars, mustBeAtEnd) { //set up functions this.doValidate = validateWildcard; //set up validation parameters this.field = field; this.humanReadableName = humanReadableName; this.minChars = minChars; this.mustBeAtEnd = mustBeAtEnd; this.stopValidation = false; this.errorMessage = ""; return this; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Custom Validator // function CustomValidator(valFunction, field, defaultErrorMessage) { this.doValidate = valFunction; //set up validation parameters this.field = field; this.stopValidation = false; this.errorMessage = defaultErrorMessage; return this; }