正则表达式验证手机号码,java正则表达式验证手机号码
1
index.jsp
注册信息填写页,同时会将输入错误的数据进行错误提示
2
check.jsp
将输入的表单数据自动赋值给JavaBean,同时进行验证,如果失败则返回index.jsp
3
success.jsp
注册成功页,可以显示出用户注册成功的信息
4
Zhuche.java
注册使用的JavaBean,可以接收参数,同时进行判断,并返回错误的结果
程序中由于错误不固定,所以使用Map接口类型保存所有的错误信息。Zhuche.java(javabean)代码:
package cn.mypro.java.demo;import java.util.HashMap;
import java.util.Map;
public class Zhuche{
private String name;
private String age;
private String email;
private Map errors=null;
public Zhuche(){
this.name=""; //初始化空值,防止出现null错误
this.age=""; //初始化空值,防止出现null错误
this.email=""; //初始化空值,防止出现null错误
this.errors=new HashMap();
}
public boolean isValidate(){
boolean flag=true;
if(!this.name.matches("\\w{6,15}")){ //运用正则表达式判断输入的用户名称格式是否正确
flag=false;
this.name="";
this.errors.put("errname","用户名错误,必须为6~15位的数字或字母.");
}
if(!this.age.matches("\\d+")){ //运用正则表达式判断输入的年龄格式是否正确
flag=false;
this.age="";
this.errors.put("errage","年龄错误.");
}
if(!this.email.matches("\\w+@\\w+.\\w+\\.?\\w*")){ //运用正则表达式判断输入的邮箱格式是否正确
flag=false;
this.email="";
this.errors.put("erremail","邮箱错误,请确认书写格式是否正确.");
}
return flag; //返回标记
}
public String getErrorMsg(String key){
String value=this.errors.get(key);
return value==null?"":value; //判断value的值是否为null,如果是则取空值””,否则取原值
}
public void setName(String name){
this.name=name;
}
public void setAge(String age){
this.age=age;
}
public void setEmail(String email){
this.email=email;
}
public String getName(){
return this.name;
}
public String getAge(){
return this.age;
}
public String getEmail(){
return this.email;
}
}
index.jsp页面代码:
www.java.com
<%
request.setCharacterEncoding("GBK");
%>
用户名:"/>
年 龄:
E-mail:"/>
Success.jsp页面代码:
www.java.com
<%
request.setCharacterEncoding("GBK");
%>
用户名:
年 龄:
E-mail:
Check.jsp页面代码:
www.java.com
<%
request.setCharacterEncoding("GBK");
%>
<%
if(zhuche.isValidate()){
%>
<%
}else{
%>
<%
}
%>
本实例程序完全利用了JavaBean的自动赋值以及request保存范围的特点完成。
(本文由沙海孤尘原创,欢迎关注,带你一起长知识!)
赞
