struts表单验证xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="user.username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空</message> </field-validator> <!-- 验证用户名只能是字母或数字,长度在6-25之内 --> <field-validator type="regex"> <param name="expression"> <![CDATA[(\w{6,25})]]> </param> <message>您输入的用户名必须在6-25个字符内,并且只允许字母和数字</message> </field-validator> </field> <!-- 重点 --> <field name="user.password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">18</param> <message>密码长度必须在6-18个字符内</message> </field-validator> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[(user.password==user.repassword)]]></param> <message>两次密码必须一致</message> </field-validator> </field> <!-- 重点 --> <field name="user.age"> <field-validator type="int"> <param name="min">0</param> <param name="max">150</param> <message>年龄范围不正确</message> </field-validator> </field> <field name="user.email"> <field-validator type="email"> <message>邮箱格式不正确:例如(example@163.com)</message> </field-validator> </field> <field name="user.phone"> <field-validator type="regex"> <param name="expression"><![CDATA[^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8})|(0\d{2}-\d{7,8})|(0\d{3}-\d{7,8})$]]></param> <message>电话号码不符合规范!xxxxxxxxxxx或05xx-xxxxxx或 010-xxxxxxxx</message> </field-validator> </field> </validators>
1:放置位置和目录结构
2:action
package com.test.action; import com.opensymphony.xwork2.ActionSupport; import com.test.bean.Users; public class RegisterAction extends ActionSupport { private Users user; @Override public String execute() throws Exception { return SUCCESS; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } }
3:index.jsp页面展示
<form action="<%=path %>/test/registerAction" method="post"><!--必须要带[0],除[] --> 用户名:<input type="text" name="user.username"/>${errors["user.username"][0]}<br><br> 密码:<input type="password" name="user.password"/>${errors["user.password"][0]}<br><br> 确认密码:<input type="password" name="user.repassword"/>${errors["user.repassword"][0]}<br><br> 年龄:<input type="text" name="user.age"/>${errors["user.age"][0]}<br><br> 邮箱:<input type="text" name="user.email"/>${errors["user.email"][0]}<br><br> 电话:<input type="text" name="user.phone"/>${errors["user.phone"][0]}<br><br> <input type="submit" value="提交"/> </form>