Struts 2 Date Validation Example
Last Updated :
28 Apr, 2025
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"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<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.
Similar Reads
Struts 2 Email Validation EmailValidator verifies that a given String field, if not empty, has a valid email address. It is utilized. Check to ensure that the string field has a valid email address and is not empty. Struts 2 validation is specified via XML or annotations. Manual validation within the action is also feasible,
3 min read
Struts 2 double validation The Struts 2 Framework's Double Validator determines whether or not the input is double. The error message is generated if the input is not twice. The input range can also be verified using a double validator. This example shows how to check the input range using a double validator. Plain validator
3 min read
Struts 2 Int Validation Struts 2 integer validator is used to determine whether an integer field is inside a certain range. There are two ways to use this validator, much as other Struts validators. The Field Validator verifies if the entered number falls into the defined range. Example of Struts 2 int validationXML <va
3 min read
Struts 2 requiredstring Validation Example Struts 2 is a strong framework for creating Java web applications. Its strong validation system, which enables developers to verify user input easily, is one of its primary strengths. Specifically, we'll cover Struts 2 needed string validation in this post, showing you how to make sure particular fi
5 min read
Data Validation in Excel Data Validation gives you the control to receive particular inputs from users. We all have encountered using this feature in our day-to-day lives, one such example is while filling out forms in which the age cell will accept numbers, the name column accepts text with limited characters, and the date
6 min read
Ruby on Rails Validation Ruby on Rails (often just Rails) is a popular web application framework written in Ruby. One of its core features is validation, which ensures that data entered into a Rails application meets specific criteria before being saved to the database. Validations help maintain data integrity, enhance user
7 min read