Last active
March 22, 2018 16:07
-
-
Save DCCoder90/d178159cb4fe31e06393118efe01534a to your computer and use it in GitHub Desktop.
A small, quick, and simple method of verify fields in a form.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Name: restrictInput | |
Signature: restrictInput(string type, event keypress); | |
Description: Restricts input to fields to specified values | |
Usage: $("#myfieldID").keydown(function(e)){ | |
restrictInput("alpha",e); | |
}; | |
Types: | |
alphanumeric - All letters and numbers | |
digit - Numbers only | |
letters - Letters only, to include upper and lower case | |
================================================================================ | |
Name: autoVerify | |
Signature:bool autoVerify(string classname,bool highlightFields, bool showErrors) | |
Description: Performs automatic verification of specified fields | |
Usage: if(autoVerify("myclass", true, false)){ | |
alert("Fields are valid!"); | |
}else{ | |
alert("Fields are not valid!"); | |
} | |
Details: In order for the auto verify to work properly the fields are required to have | |
specific HTML attributes. These attributes and their purposes are defined below. | |
Required? Attribute Purpose | |
------------------------------------------------------------------------------------------------------------------------ | |
Y | id | Required field, allows highlighting and field identification | |
Y | valid-name | Gives the field a user-friendly name for display purposes | |
N | valid-type | Specifies the type of validation to be performed (string, number, money, or email [Default: string]) | |
N |valid-required | Specifies whether the field is required or not | |
N | valid-min | Specifies the minimum acceptable value. (For number or money this is a defined amount, for string it is the string length) | |
N | valid-max | Specifies the maximum acceptable value. (For number or money this is a defined amount, for string it is the string length) | |
=============================================================================== | |
Name: getAutoVerifyObj | |
Signature: getAutoVerifyObj(string className) | |
Description: Generates objects for use by the verifyFields function from CSS class name. See the table under autoVerify for further details. | |
Usage: var fields = getAutoVerifyObj("myclassname"); | |
if(verifyFields(fields,true,false)){ | |
alert("Fields are valid!"); | |
}else{ | |
alert("Fields are not valid!"); | |
} | |
=============================================================================== | |
Name: verifyFields | |
Signature:bool verifyFields(obj[] fields, bool highlightFields, bool showError) | |
Description: Performs validation on a collection of field objects | |
Usage: var field = new { id: "myfield", name:"somefield", type: "string", required: true}; | |
var fields[] = {field}; | |
if(verifyFields(fields,true,false)){ | |
alert("Fields are valid!"); | |
}else{ | |
alert("Fields are not valid!"); | |
} | |
Details: Performs manual validation on supplied fields. Best to use autoVerify rather than using this, or use the getAutoVerifyObj in conjuction | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatMoney(className) { | |
if (className === undefined) { | |
className = "money"; | |
} | |
var elements = $("." + className); | |
var numString = elements.text(); | |
var numFloat = parseFloat(numString); | |
//Ensure that decimal places only go to 2 | |
var digitMatch = ('' + numString).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); | |
if (match) { | |
var digitPlacement = Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)); | |
if (digitPlacement > 2) { | |
elements.text(numFloat.toFixed(2)); | |
} | |
} | |
elements.prepend("$"); | |
} | |
function cleanNumber(mystring) { | |
if (mystring === undefined) { | |
return undefined; | |
} | |
var cleanedNumber; | |
cleanedNumber = mystring.replace(/[^0-9\.\-]/g, ''); | |
return cleanedNumber; | |
} | |
function getAutoVerifyObj(className) { | |
var objArr = Array(); | |
$("." + className).each(function (i, obj) { | |
var validType = $(this).attr('valid-type'); | |
var validName = $(this).attr('valid-name'); | |
var id = $(this).attr('id'); | |
var required = $(this).attr('valid-required'); | |
var min = $(this).attr('valid-min'); | |
var max = $(this).attr('valid-max'); | |
var obj = { id: id, name: validName }; | |
if (isDefined(validType)) { | |
obj.type = validType; | |
} | |
if (isDefined(required)) { | |
obj.required = required; | |
} | |
if (isDefined(min)) { | |
obj.min = min; | |
} | |
if (isDefined(max)) { | |
obj.max = max; | |
} | |
objArr.push(obj); | |
}); | |
return objArr; | |
} | |
function restrictInput(type,event) { | |
if (type === undefined) { | |
type = "alphanumeric"; | |
} | |
var digits = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57]; | |
var numpad = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105]; | |
var letters = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]; | |
var navigation = [35, 36, 37, 38, 39, 40]; | |
var control = [8, 9, 13, 16, 17, 18, 19, 20, 27, 33, 34, 45, 46]; | |
var special = [106,107,109,110,111,186,187,188,189,190,191,192,219,220,221,222]; | |
if (type == "alphanumeric") { | |
if (($.inArray(event.keyCode, digits) !== -1) || | |
($.inArray(event.keyCode, letters) !== -1) || | |
($.inArray(event.keyCode, control) !== -1) || | |
($.inArray(event.keyCode, navigation) !== -1) || | |
($.inArray(event.keyCode, numpad) !== -1)) { | |
return; | |
} else { | |
event.preventDefault(); | |
} | |
} | |
if (type == "digit") { | |
if (($.inArray(event.keyCode, digits) !== -1) || //Check if digit | |
($.inArray(event.keyCode, navigation) !== -1) || | |
($.inArray(event.keyCode, control) !== -1) || | |
($.inArray(event.keyCode, numpad) !== -1)) { //Check if numpad digit | |
return; | |
} else { | |
event.preventDefault(); | |
} | |
} | |
if (type == "letters") { | |
if (($.inArray(event.keyCode, letters) !== -1) || | |
($.inArray(event.keyCode, navigation) !== -1) || | |
($.inArray(event.keyCode, control) !== -1) | |
) { //Check if letter | |
return; | |
} else { | |
event.preventDefault(); | |
} | |
} | |
return; | |
} | |
function autoVerify(className,highlightFields,showError){ | |
if(highlightFields === undefined){ | |
highlightFields = false; | |
} | |
if(showError === undefined){ | |
showError = false; | |
} | |
var objArr = Array(); | |
$("."+className).each(function(i, obj) { | |
var validType = $(this).attr('valid-type'); | |
var validName = $(this).attr('valid-name'); | |
var id = $(this).attr('id'); | |
var required = $(this).attr('valid-required'); | |
var min = $(this).attr('valid-min'); | |
var max = $(this).attr('valid-max'); | |
var obj = {id:id,name:validName}; | |
if(isDefined(validType)){ | |
obj.type = validType; | |
} | |
if(isDefined(required)){ | |
obj.required = required; | |
} | |
if(isDefined(min)){ | |
obj.min = min; | |
} | |
if(isDefined(max)){ | |
obj.max = max; | |
} | |
objArr.push(obj); | |
}); | |
return verifyFields(objArr,highlightFields,showError); | |
} | |
function isDefined(object){ | |
if(typeof(object)!== typeof(undefined) && object !==false && object !== undefined){ | |
return true; | |
} | |
return false; | |
} | |
function validateEmail(emailField) { | |
var reg = /^(([^<>()\[\]\\.,;:\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,}))$/; | |
if (reg.test(emailField) == false) { | |
return false; | |
} | |
return true; | |
} | |
function verifyFields(fields, highlightFields, showError) { | |
if (showError === undefined) { | |
showError = false; | |
} | |
if (highlightFields === undefined) { | |
highlightFields = false; | |
} | |
var errorCount = 0; | |
var ValidationErrors = Array(); | |
var ValidationFields = Array(); | |
var ValidationReason = Array(); | |
fields.forEach(function (field) { | |
if (!("id" in field)) { | |
alert("Field ID not defined!"); | |
return; | |
} | |
if (!("name" in field)) { | |
alert("Field name not defined!"); | |
return; | |
} | |
var fieldType = field["type"]; | |
var fieldId = field["id"]; | |
var fieldName = field["name"]; | |
var fieldValue = $("#" + fieldId).val(); | |
//Remove old css classes | |
$("#" + fieldId).removeClass('invalidfield'); | |
//Different methods between checking empty inputs and selects | |
if (fieldType != "select") { | |
if ("required" in field) { | |
if (new Boolean(field["required"])) { | |
if ($("#" + fieldId).val() == "") { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is required."; | |
errorCount += 1; | |
} | |
} | |
} | |
} else { | |
if ("required" in field) { | |
if (new Boolean(field["required"])) { | |
if ($("#" + fieldId + " :selected").val() == "") { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is required."; | |
errorCount += 1; | |
} | |
} | |
} | |
} | |
switch (fieldType) { | |
case "email": | |
if (!validateEmail(fieldValue)) { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is not a valid email."; | |
errorCount += 1; | |
} | |
break; | |
case "number": | |
case "money": | |
if (!jQuery.isNumeric(cleanNumber(fieldValue))){ | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is not a valid number."; | |
errorCount += 1; | |
} | |
if ("min" in field) { | |
var min = field["min"]; | |
if (parseFloat(fieldValue) < parseFloat(min)) { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is below the minimum value."; | |
errorCount += 1; | |
} | |
} | |
if ("max" in field) { | |
var max = field["max"]; | |
if (parseFloat(fieldValue) > parseFloat(max)) { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is above the maximum value."; | |
errorCount += 1; | |
} | |
} | |
break; | |
//String | |
default: | |
if ("min" in field) { | |
var min = field["min"]; | |
if (fieldValue.length < parseFloat(min)) { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is below the minimum value."; | |
errorCount += 1; | |
} | |
} | |
if ("max" in field) { | |
var max = field["max"]; | |
if (fieldValue.length > parseFloat(max)) { | |
ValidationFields[errorCount] = fieldId; | |
ValidationErrors[errorCount] = fieldName; | |
ValidationReason[errorCount] = "is above the maximum value."; | |
errorCount += 1; | |
} | |
} | |
break; | |
} | |
}); | |
//If there were any errors do the field highlighting and error display here | |
if (errorCount > 0) { | |
if (new Boolean(highlightFields)) { | |
for (var i = 0, len = ValidationErrors.length; i < len; i++) { | |
$("#"+ValidationFields[i]).addClass('invalidfield'); | |
} | |
} | |
if (new Boolean(showError)) { | |
var errorMessage = "Please enter valid input in the following fields:<br/><ul>"; | |
//For loop crafts error message | |
for (var i = 0, len = ValidationErrors.length; i < len; i++) { | |
errorMessage = errorMessage + "<li>"+ValidationErrors[i]+ " " + ValidationReason[i] + "</li>"; | |
} | |
errorMessage = errorMessage + "</ul>"; | |
//Dependant on | |
createErrorDialog(errorMessage); | |
} | |
return false; | |
} | |
return true; | |
} | |
function createErrorDialog(errorMessage){ | |
var dialogHtml = "<div id=\"error-dialog\" title=\"Error Message\"><div class=\"dialog-message\"></div></div>"; | |
$(document.body).append(dialogHtml); | |
$("#error-dialog").dialog({ | |
modal: true, | |
draggable: false, | |
resizable: true, | |
position: ['center','top'], | |
show: 'blind', | |
hide: 'blind', | |
width: 400, | |
buttons: { | |
"Close": function(){ | |
destroyErrorDialog(); | |
} | |
} | |
}); | |
$("#error-dialog .dialog-message").html(errorMessage); | |
$("#error-dialog").dialog("open"); | |
} | |
function destroyErrorDialog(){ | |
$("#error-dialog").remove(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment