Struts 2 requiredstring Validation Example
Last Updated :
24 Apr, 2025
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 fields aren't null or empty. This is an essential component of web development to improve user experience and data integrity.
Validation XML files are the main tool used to do Struts 2 validation. These files provide guidelines that specify how input validation should be done. We will pay close attention to making sure that certain fields are not empty for necessary string validation. The essential element for this job is the required string validator.
Prerequisites
Before doing the string validation needed by Struts 2, confirm that you have the following setup:
XML file for Validation
To begin, build an XML file for your action's validation. The name pattern for this file is usually "ActionClassName-validation.xml" The validation file might be called UserAction-validation.xml, for instance, if your action class is UserAction.
XML
<!-- UserAction-validation.xml -->
<!DOCTYPE validators PUBLIC "-//OpenSymphony//XWork Validator 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>Your username is required.</message>
</field-validator>
</field>
<!-- Add more fields as needed -->
</validators>
We are making sure that the username field is a mandatory string in this case.
Struts Configuration Validation File
Ensure that the validation file is referenced in your struts.xml settings.
XML
<!-- struts.xml -->
<package name="default" extends="struts-default">
<action name="userAction" class="com.example.UserAction">
<result>/user.jsp</result>
<result name="input">/login.jsp</result>
<!-- Reference the validation file -->
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow"/>
</action>
</package>
Make that the "validation" interceptor's <interceptor-ref> is included.
Handling Validation Errors in Action Class
Provide the required getters and setters for the fields you are verifying in your action class. Use the validate function to handle validation problems as well.
Java
// UserAction.java
public class UserAction extends ActionSupport {
private String username;
// Getter and Setter for username
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public void validate() {
if (username == null || username.trim().isEmpty()) {
addFieldError("username", "Username is required.");
}
// Add more validation logic as needed
// Example: Validate if the username contains only alphanumeric characters
if (!username.matches("^[a-zA-Z0-9]+$")) {
addFieldError("username", "Username should contain only letters and numbers.");
}
}
// Action method for handling the form submission
public String submitForm() {
if (hasErrors()) {
// If there are validation errors, return INPUT to display the form again
return INPUT;
}
// Business logic: Perform actions based on the user input
// Example: Save the username to a database
// userService.saveUsername(username);
// Return a success result
return SUCCESS;
}
// Other action methods
// Action method to display a welcome message
public String welcomeMessage() {
// Business logic: Generate a welcome message based on the username
// Example: Fetch additional user information and display a personalized welcome
// String welcomeMessage = userService.generateWelcomeMessage(username);
// addActionMessage(welcomeMessage);
addActionMessage("Welcome, " + getUsername() + "!");
return SUCCESS;
}
}
Explanation of the above Program:
- To access and change the value of the username field, getter and setter methods are provided.
- The necessary string validation for the username field is carried out using the validate method. This approach may be expanded to include more validation logic as required.
- One example of an action method that manages form submission is the submitForm method. It executes business logic and delivers the SUCCESS result if there are no validation issues, otherwise it returns the INPUT result to show the form once again.
- To show you how to have more than one action method in the same class, below is an extra action method called welcomeMessage.
These examples demonstrate fundamental business logic in the action methods (submitForm and welcomeMessage) and additional validation logic in the validate function. Adapt the code to the requirements of your application and include any service or database interfaces that are required.
Example of Struts 2 requiredstring Validation
Let's look at a simple login form that has a username field. The validation framework will intercept the request, carry out the necessary string validation, and reroute the user back to the form with the relevant error messages when they submit the form without providing a username.
Login form (login.jsp):
<form action="userAction" method="post">
Username: <input type="text" name="username"/>
<input type="submit" value="Submit"/>
</form>
Handling Validation Errors (user.jsp):
<s:fielderror/>
<form action="userAction" method="post">
Username: <input type="text" name="username"/>
<input type="submit" value="Submit"/>
</form>
The <s:fielderror/> tag will display the validation error message.
Conclusion
With the robust and adaptable validation architecture that Struts 2 offers, developers may easily enforce necessary string validation. Your web apps' dependability and usability may be improved by using the procedures described in this article. Use these methods in your Struts 2 applications to build user input forms that are reliable and verified.
Similar Reads
Struts 2 String Length Validation
The string length field validator makes sure that a string field's length, such as a password's 6â12 characters, stays within a certain range. Using the stringlength property in elements or annotation types may be applied to XML or annotations. The String will have at least that many characters if t
3 min read
Struts 2 Date Validation Example
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 valid
3 min read
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 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 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
Spring - MVC Regular Expression Validation
Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation. Syntax: @Pattern(regex="", flag="", message="") private Strin
4 min read
Struts 2 Custom Validation - Workflow Interceptor
Struts 2 allows us to design our validation logic, commonly known as custom validation, by implementing the action class's Validatable Interface. As you might expect, understanding the Validatable interface is critical for understanding Struts2 custom validation. Workflow InterceptorThe workflow int
3 min read
Semantic-UI Form Field Required Variation
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. A form is the section of a document that
2 min read
Spring - MVC Validation
The Spring MVC framework provides us with standard predefined validators to validate user input data in a simple and straightforward way. The Bean Validation API is the popular approach for data validations in Spring applications. Here we will be using the hibernate implementation of the Bean Valida
5 min read
Spring MVC - Number Validation
The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
9 min read