@RequiredFieldValidator and @StringLengthFieldValidator in Struts 2

By Arvind Rai, June 15, 2014
In this page, we will understand how to use @RequiredFieldValidator and @StringLengthFieldValidator annotation in struts 2. These annotations are used to validate form fields. @RequiredFieldValidator checks whether a field is empty or not. @StringLengthFieldValidator is used to check if the length of string entered by the user is in given range or not.

@RequiredFieldValidator Annotation in Struts 2

@RequiredFieldValidator checks for a field that user has entered a value or not. If no value is filled, an error message will be displayed.

message : This attribute is required. This displays the error message.
key : This is I18 key which is obtained from property file.
type : The value of type can be like ValidatorType.FIELD enum.

Syntax
@RequiredFieldValidator(message = "Default message", key = "msg.i18n.key", shortCircuit = true) 
How to use in the code.
public class UserAction extends ActionSupport{
	private String name;
	public String execute() {
	   return SUCCESS; 
	}
	@RequiredFieldValidator(message = "Please enter a value.")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 

@StringLengthFieldValidator Annotation in Struts 2

@StringLengthFieldValidator checks the length of string in the form field. It assumes every thing string and gets length and checks if it is in given length range. If min and max is not set, it will do nothing.

message : This attribute is required. This displays the error message.
key : This is I18 key which is obtained from property file.
type : The value of type can be like ValidatorType.FIELD enum.
min : Minimum value of integer entered by user.
max: Maximum value of integer entered by user.
trim: This is a Boolean property and if true, String is trimmed before getting length.

Syntax
@StringLengthFieldValidator(message = "Default message", key = "msg.i18n.key", shortCircuit = true, trim = true, minLength = "15",  maxLength = "30") 
How to use in the code.
public class UserAction extends ActionSupport{
	private String name;
	public String execute() {
	   return SUCCESS; 
	}
	@StringLengthFieldValidator(message = "Enter value between 15 and 30", trim = true, minLength = "15",  maxLength = "30")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us