I am doing an XML form validation and form validation with validate() method. The XML validation is to check if they filled out the required fields, are the fields in proper length and etc. while the validate method performs database look up if the entered value exist in the database. if it does exist it will add a field error.
Now my problem. when I submit the form and I did not fill out the requiredstrings it will add an error to page, but when I enter a valid value it still prompts the same error(and at the same time it does not call the validate method).
this is my form.
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head/>
</head>
<body>
<h3>Register for a prize by completing this form.</h3>
<div id="divErrors">
</div>
<s:form action="register" id ="result">
<label>UserName</label>
<s:textfield name="userBean.username" />
<s:fielderror/>
<sj:submit
targets="result"
value="AJAX Submit"
indicator="indicator"
button="true"
/>
</s:form>
</body>
</html>
Register-validation.xml
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="userBean.username">
<field-validator type="requiredstring">
<message>User name is required.</message>
</field-validator>
</field>
</validators>
And my validate from the RegisterAction class.
public void validate(){
if(userBean != null && userBean.getUsername().equals("foo")){
this.addFieldError("userBean.username", "That Username already exist");
}
}
The Scenario what I am doing.
I will submit the form without filling up the required string, and then I will enter a valid value, after the submitting the form the same error still exist.
Actually the problem is that the validation framework in Struts2 by default returns the input result if the validation fails. If the input is the JSP page that is the form inside, then as you make ajax call then the whole page will be replaced.
Second time you've made the valid call, so after the validation the execute method should return the result. And this result should be the JSP fragment that replaced on the page at the target "result", that is the form element. But the div "divErrors" is not replaced by your code. If it had errors rendered on the first request, then it will be there.
Ok, I think it worth enough to make understanding ajax and validation. And you understand now how to solve the problem that returns result that is not expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With