struts2同样支持客户端验证
1. struts2标签的form的主题(theme)一定不能设为simple。
2. 将form的validate属性设为true。
这样客户端就会根据相应的action的xml验证文件产生一个js对客户端进行验证。
一般开发中只使用struts2的服务端验证,而不使用struts2的客户端验证,因为它的格式太死板。
我们可以自己写js来进行客户端的验证。
regist2.jsp
<script type="text/javascript">
function validate() {
//document.getElementsByName("username")[0].value;
因为表单中可能有多个元素叫username,因此用getElements;又因此表单中实际只有一个因此取下标为
0的那个。取其值用.value
var usernameValue = document.getElementById("usernameId").value;
var passwordValue = document.getElementById("password").value;
var repasswordValue = document.getElementById("repassword").value;
if(usernameValue.length == 0) {
alert("username should not be blank!");
return false;
}
else if(usernameValue.length < 6 || usernameValue.length > 10) {
alert("length of username should be between 6 and 10!");
return false;
}
if(passwordValue.length == 0) {
alert("password should not be blank!");
return false;
}
else if(passwordValue.length < 6 || passwordValue.length > 10) {
alert("length of password should be between 6 and 10!");
return false;
}
if(repasswordValue.length == 0) {
alert("repassword should not be blank!");
return false;
}
else if(repasswordValue.length < 6 || repasswordValue.length > 10) {
alert("length of repassword should be between 6 and 10!");
return false;
}
if(passwordValue != repasswordValue) {
alert("password and repassword should be same!");
return false;
}
return true;
}
</script>
<s:form action="register" theme="simple" οnsubmit="return validate();">
<table align="center" width="40%" border="1">
<tr>
<td>
username
</td>
<td>
<s:textfield name="username" label="username" id="usernameId"></s:textfield>
</td>
</tr>
<tr>
<td>
password
</td>
<td>
<s:password name="password" label="password" id="passwordId"></s:password>
</td>
</tr>
<tr>
<td>
re-password
</td>
<td>
<s:password name="repassword" label="repassword" id="repasswordId"></s:password>
</td>
</tr>
</table>
</s:form>
struts2的action中可以有多个方法,若我们只想对其中的一个方法进行验证的话,可以提供如下文件:
如对RegistAction中的test方法进行验证,须要RegistAction-test-validation.xml文件,路径与其action一至。
若同时出现RegistAction-test-validation.xml与RegistAction-validation.xml两个文件,则会先执行RegistAction-tvalidation.xml的校验,再执行RegistAction-test-validation.xml的校验。
若出现继承的action时,如:
ParrentAction {
test(){...}
}
ParrentAction-validation.xml
ParrentAction-test-validation.xml
ChildAction extence ParrentAction {
test(){...}
}
ChildAction-validation.xml
ChildAction-test-validation.xml
若要对childAction中的test方法进行验证,则系统会按照以上文件的顺序进行4次验证。