Created
May 12, 2013 15:21
-
-
Save stephenfeather/5563899 to your computer and use it in GitHub Desktop.
Simple validation and typing functions
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
exports.trim = function(s) { | |
//alert('hi'); | |
var l = 0; | |
var r = s.length - 1; | |
while (l < s.length && s[l] == ' ') { | |
l++; | |
} | |
while (r > l && s[r] == ' ') { | |
r -= 1; | |
} | |
return s.substring(l, r + 1); | |
}; | |
exports.validateEmail = function(value, alerts){ | |
var success; | |
var message = ""; | |
var tfld = exports.trim(value); | |
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ; | |
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; | |
if (value === "") { | |
message = "You didn't enter an email address."; | |
success=false; | |
} else if (!emailFilter.test(tfld)) { //test email for illegal characters | |
message = "Please enter a valid email address."; | |
success=false; | |
} else if (value.match(illegalChars)) { | |
message = "The email address contains illegal characters."; | |
success=false; | |
} else { | |
success = true; | |
} | |
if (alerts && !success){ | |
alert(message); | |
} | |
return success; | |
} | |
exports.validatePhone = function(value, alerts){ | |
var success; | |
var message = ''; | |
var stripped = value.replace(/[\(\)\.\-\ ]/g, ''); | |
if (value === "") { | |
message = "You didn't enter a phone number."; | |
success = false; | |
} else if (isNaN(stripped)){ | |
message = "The phone number contains illegal characters."; | |
success = false; | |
} else if (!(stripped.length == 10)){ | |
message = "The phone number is the wrong length. Make sure you included an area code."; | |
success = false; | |
} else { | |
success = true; | |
} | |
if (alerts && !success){ | |
alert(message); | |
} | |
return success; | |
} | |
exports.phoneOrEmail = function(value){ | |
var phone = exports.validatePhone(value, false); | |
var email = exports.validateEmail(value, false); | |
var type; | |
if (phone){ | |
type = 'phone'; | |
} else if (email){ | |
type = 'email'; | |
} else { | |
type = 'none'; | |
} | |
return type; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment