常用验证
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><script type="text/javascript" src="jquery-1.8.1.js"></script><script type="text/javascript" src="myjs.js"></script></head><body><table><tr><td>用户名:</td><td><input type="text" id="username" onblur="checkStrNotNull('用户名','username',true)"></td></tr><tr><td>年龄:</td><td><input type="text" id="age" onblur="checkIsNum('年龄','age',true)"/></td></tr><tr><td>电话号码:</td><td><input type="text" id="phoneNum" onblur="checkIsPhoneNum('电话号码','phoneNum',true)"/></td></tr><tr><td>电子邮箱:</td><td><input type="text" id="mail" onblur="checkIsMail('电子邮箱','mail',true)"/></td></tr></table></body></html>
myjs.js
function checkStrNotNull(showtext,id,isFocus){if($("#"+id).val()==null||$("#"+id).val()==""){alert(showtext+"不能为空!");if(isFocus){$("#"+id).focus();}return false;}return true;}function checkIsNum(showtext,id,isFocus){if(isNaN($("#"+id).val())){alert(showtext+"必须为数字!");if(isFocus){$("#"+id).focus();}return false;}return true;}function checkIsPhoneNum(showtext,id,isFocus){var isMobile=/^(?:13\d|15\d|18\d)\d{5}(\d{3}|\*{3})$/; var isPhone=/^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;var value = $("#"+id).val();if(!isMobile.test(value) && !isPhone.test(value)){alert("请正确填写电话号码,例如:13415764179或0321-4816048"); return false;}return true;}function checkIsMail(showtext,id,isFocus){var isMail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;var value=$("#"+id).val();if(!isMail.test(value)){alert(showtext+"格式不正确!");return false;}return true;}