1.
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 7 <title>表单验证之使用正则表达式验证字段</title> 8 <style type="text/css"> 9 .label {float:left; width:120px;} 10 .infobox {width: 200px; } 11 .error {color:red; padding-left: 10px;} 12 .submit {margin-left: 125px; margin-top: 10px; } 13 </style> 14 <script src="jquery-1.5.2.js" type="text/javascript"></script> 15 <script type="text/javascript"> 16 $(document).ready(function(){ 17 $('.error').hide(); 18 $('.submit').click(function(event) { 19 var data = $('.infobox').val(); 20 if(validate_phoneno(data)){ 21 $('.error').hide(); 22 } 23 else { 24 $('.error').show(); 25 event.preventDefault(); 26 } 27 }); 28 }); 29 function validate_phoneno(ph) { 30 var pattern = new RegExp(/^[0-9-+]+$/); 31 //年份正则表达式 /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/ 32 //\b在正则表达式的开头和结尾,表示单词边界,即单词必须与模式完全匹配 33 return pattern.test(ph); 34 } 35 </script> 36 <body> 37 <form id="signup" method="post" action=""> 38 <div> 39 <span class="label">Phone Number *</span> 40 <input type="text" class="infobox" name="userid" /> 41 <span class="error">Check the format of phone number!</span> 42 </div> 43 <input class="submit" type="submit" value="submit" /> 44 </form> 45 </body> 46 </html>