Open In App

Struts 2 Date Validation Example

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Struts 2, a powerful web application framework for Java, offers robust support for form validation. Custom validation allows developers to enforce specific rules on user inputs, ensuring data integrity and providing meaningful error messages. In this guide, we’ll delve into the world of custom validation in Struts 2 by creating a practical example.

Struts 2 Date Validation

Custom validation in Struts 2 is achieved by extending the ActionSupport class and overriding the validate method. This method is automatically invoked before the execution of the action’s business logic. We’ll demonstrate this with a scenario where we validate a user’s birth date to ensure it is not only required but also follows a specific format.

Step by Step Implementation

Step 1. Create the Action Class (YourAction.java)

Java




// YourAction.java
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
  
@Action(value = "yourAction", results = {
        @Result(name = "success", location = "/success.jsp"),
        @Result(name = "input", location = "/yourForm.jsp")
})
public class YourAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
  
    private String birthDate;
  
    // Getter and Setter for birthDate
  
    @Override
    public void validate() {
        if (birthDate == null || birthDate.trim().isEmpty()) {
            addFieldError("birthDate", "Birth Date is required");
        } else {
            // Perform additional validation if needed
            // For simplicity, let's assume a valid date is required
            if (!isValidDate(birthDate)) {
                addFieldError("birthDate", "Invalid date format");
            }
        }
    }
  
    private boolean isValidDate(String date) {
        // You can use a SimpleDateFormat or another date parsing mechanism
        // Here, we'll just check if it's a valid date format (MM/dd/yyyy)
        // This is a simple example; in a real-world application, you'd use
          // a more robust date parsing/validation mechanism
        return date.matches("\\d{2}/\\d{2}/\\d{4}");
    }
  
    public String execute() {
        // Your action logic here
        return SUCCESS;
    }
}


Step 2. Create the Form Class (YourForm.java)

Java




// YourForm.java
  
import org.apache.struts.action.ActionForm;
  
public class YourForm extends ActionForm {
    private static final long serialVersionUID = 1L;
    private String birthDate;
  
    // Getter and Setter for birthDate
}


Step 3. Configure Validation (validation.xml)

XML




<!-- validation.xml -->
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  
<validators>
    <field name="birthDate">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message key="errors.required" />
        </field-validator>
    </field>
</validators>


Step 4. Create the JSP Page (yourForm.jsp)

HTML




<!-- yourForm.jsp -->
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
  
<html>
<head>
    <title>Your Struts 2 App</title>
</head>
<body>
    <s:form action="yourAction">
        <s:textfield label="Birth Date" name="birthDate" />
        <s:submit />
    </s:form>
</body>
</html>


Step 5. Run and Verify

Compile and execute your Struts 2 application. Access the form, enter a birth date, and submit the form. The custom validation will ensure that the entered date is not only required but also in the specified format.

Output:

Conclusion

Custom validation in Struts 2 empowers developers to tailor validation rules according to their application’s needs. By following this step-by-step guide, you’ve integrated custom validation into a Struts 2 application, enhancing user experience and data integrity.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads