Created
August 25, 2011 19:05
-
-
Save DfKimera/1171506 to your computer and use it in GitHub Desktop.
Form validation component
This file contains 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 validate_form(fields, invalidCallback, validCallback) { | |
if(!fields) { | |
invalidCallback(); | |
return false; | |
} | |
invalid = []; | |
for(var i in fields) { | |
f = fields[i]; | |
fld = $('#'+f.id); | |
v = true; | |
switch(f.mode) { | |
case 'number': | |
v = validate_number(fld.val(), f); | |
break; | |
case 'password': | |
v = validate_password(fld.val(), f); | |
break; | |
case 'string': | |
default: | |
v = validate_string(fld.val(), f); | |
break; | |
} | |
if(!v) { | |
invalid.push(f.label); | |
} | |
} | |
if(invalid.length > 0) { | |
invalidCallback(invalid); | |
return false; | |
} else { | |
validCallback(fields); | |
return true; | |
} | |
} | |
function validate_string(value, f) { | |
if(value == null || value == "" || value == undefined) { | |
return false; | |
} | |
if(typeof value != 'string') { | |
return false; | |
} | |
if(value.length < f.min || value.length > f.max) { | |
return false; | |
} | |
return true; | |
} | |
function validate_number(value, f) { | |
if(value == null || value == "" || value == undefined) { | |
return false; | |
} | |
try { | |
value = parseInt(value); | |
} catch(e) { | |
return false; | |
} | |
if(value == f.incorrect) { | |
return false; | |
} | |
return true; | |
} | |
function validate_password(value, f) { | |
if(value == null || value == "" || value == undefined) { | |
return false; | |
} | |
if(typeof value != 'string') { | |
return false; | |
} | |
if(f.compare) { | |
compareValue = $('#'+f.compare).val(); | |
if(!validate_string(compareValue)) { | |
return false; | |
} | |
if(value != compareValue) { | |
return false; | |
} | |
} | |
if(value.length < f.min) { | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment