Sometimes it becomes necessary to process user input client side. It saves the user a lot of time if he/she is notified of errors in his/her errors before submitting the form. This example contains two functions for validating email addresses and urls.
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>JavaScrip URL & Email Validation</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
<!--
function isValidURL(url){
var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
if(RegExp.test(url)){
return true;
}else{
return false;
}
}
function isValidEmail(email){
var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/
if(RegExp.test(email)){
return true;
}else{
return false;
}
}
function checkField(){
var frm = document.frmValidate, error = "";
if(!isValidURL(frm.url.value)){
error += "Please enter a valid URL\n";
}
if(!isValidEmail(frm.email.value)){
error += 'Please enter a valid Email\n';
}
if(error != ""){
alert(error);
return false;
}else{
return true;
}
}
Tim N wrote :1805
the URL regex does not work for URLs with commas in them (ex: http://www.latimes.com/news/local/la-me-textbook18-2008aug18,0,7294220,full.story)
this one works for me on those url's
var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([,-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([,-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([,-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
(note: logged in using bugmenot, so don't bother trying to contact me)