Validations in struts
Validation
To keep away from the wrong esteems, we have to perform approval on frames where client presents a few esteems. For instance, if client composes his/her email id as abc, we have to give blunder message to the client that the given email id is not right With the goal that we can have just significant information.
There are three approaches to perform approval in struts 2.
1) By Custom Validation Here, we should execute the Validateable interface (or expand ActionSupport class) and give the usage of approve technique.
2) By Input Validation (worked in validators) Struts 2 gives a considerable measure of predefined that can be utilized as a part of struts 2 application to perform approval.
3)By Ajax Validation
we can use jsonValidation interceptor to perform validation with ajax.
Validateabale interface
The Validateable interface must be actualized to perform approval rationale in the activity class. It contains just a single strategy approve() that must be abrogated in the activity class to characterize the approval rationale. Mark of the approve technique .
public void validate();
validationAware interface
The ValidationAware interface can acknowledge the field level or activity class level blunder messages. The field level messages are kept in Map and Action class level messages are kept in accumulation. It ought to be executed by the activity class to include any mistake message.
Methods of ValidatationAware interface
| Method |
| void addFieldError(String fieldName,String errorMessage) |
| void addActionError(String errorMessage) |
| void addActionMessage(String message) |
| void setFieldErrors(Map<String,List<String>> map) |
| void setActionErrors(Collection<String> errorMessages) |
| void setActionMessages(Collection<String> messages) |
| boolean hasErrors() |
| boolean hasFieldErrors() |
| boolean hasActionErrors() |
| boolean hasActionMessages() |
| Map<String,List<String>> getFieldErrors() |
| Collection<String> getActionErrors() |
| Collection<String> getActionMessages() |
Bundled Validators
Struts 2 approval system gives many inherent validators otherwise called packaged validators for email, string, int, twofold, url, date and so forth In this way, we don't have to give express rationale to email, twofold, url and so forth. For giving particular approval rationale, we can utilize regex, which we will see later.
validation interceptor
It performs approval against the predetermined approval standards and includes the field-level and activity level mistake messages. It works in conjunction with the work process interceptor to show the mistake messages. There is no parameter characterized for this interceptor.
Favorable position of Bundled validators
Quick improvement since we don't have to determine the normal validators, for example, email date, string length and so forth.
Bundled validators
Two ways to use bundled validators
- Plain-Validator (non-field validator) Syntax
- Field-Validator Syntax
Plain-Validator (non-field validator) Syntax
<validators>
<!-- Plain-Validator Syntax -->
<validator type="requiredstring"
>
<param name="fieldName"
>username
</param>
<param name="trim"
>true
</param>
<message>username is required
</message>
</validator>
</validators>
Field-Validator Syntax
<validators>
<!-- Field-Validator Syntax -->
<field name="username"
>
<field-validator type="requiredstring"
>
<param name="trim"
>true
</param>
<message>username is required
</message>
</field-validator>
</field>
</validators>
requiredstring validation
The requiredstring validator determines that string can't be invalid or clear. It trims the string bydefault at that point checks if its length is more prominent that 0.
Parameters of requiredstring validator
example of requiredstring validator
Create index.jsp for input
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %
>
<html>
<head>
<STYLE type="text/css"
>
.errorMessage{color:red;}
</STYLE>
</head>
<body>
<s:form action="register"
>
<s:textfield name="username" label="Username"
></s:textfield>
<s:password name="userpass" label="Password"
></s:password>
<s:submit value="register"
></s:submit>
</s:form>
</body>
</html>
2) Create the action class
RegisterAction.java
package com.javaspot;
import com.opensymphony.xwork2.ActionSupport;
public class Register
extends ActionSupport{
private String username,userpass;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public String execute(){
return "success";
}
}
3) Create the validation file
Register-validation.xml
<?xml version="1.0" encoding="UTF-8"
?>
<!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="username"
>
<field-validator type="requiredstring"
>
<message>Name can't be blank
</message>
</field-validator>
</field>
</validators>
4) Create struts.xml
struts.xml
<?xml version="1.0" encoding="UTF-8"
?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"
>
<struts>
<package name="default" extends="struts-default"
>
<action name="register" class="com.javaspot.Register"
>
<result name="input"
>index.jsp
</result>
<result>welcome.jsp
</result>
</action>
</package>
</struts>
5) Create view component
It is the simple jsp file displaying the information of the user.
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %
>
Welcome,
<s:property value="username"
/>
String Length Validation
The stringlength validator indicates that string must be of given length. It can be utilized as a part of username, secret key and so on. It trims the string by default at that point checks if its length is of the given length.
Parameters of stringlength validator
| Parameter |
| fieldName |
| minLength |
| maxLength |
| trim |
Email Validation
The email validator watches that given field has substantial email address. It works just if field is not clear.
Parameters of email validator
| Parameter |
Description |
| fieldName |
specifies the field name that is to be validated. It is required in Plain-Validator only. |
Example of email validator
<validators>
<!-- Plain Validator Syntax -->
<validator type="email"
>
<param name="fieldName"
>email
</param>
<message>Please enter a valid email address
</message>
</validator>
</validators>
<validators>
<!-- Field-Validator Syntax -->
<field name="email"
>
<field-validator type="email"
>
<message>Please enter a valid email address.
</message>
</field-validator>
</field>
</validators>
Date Validation:
It will checks the date is in the specified range or not.
| Parameter |
Description |
| fieldName |
It is validated. And required in Plain-Validator only. |
| min |
minimum range. |
| max |
maximum range |
1) Create index.jsp for input
index.jsp
- <%@ taglib uri="/struts-tags"prefix="s" %>
- <s:form action="register">
- <s:textfield name="dob"label="Date of Birth"></s:textfield>
- <s:submit value="register"></s:submit>
- </s:form>
2) Create the action class
RegisterAction.java
package com.javaspot;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class Register
extends ActionSupport{
private Date dob;
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String execute(){
return "success";
}
}
3) Create the validation file
Register-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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="dob">
<field-validator type="date">
<param name="min">01/01/1950</param>
<param name="max">01/01/2010</param>
<message>Date of Birth must be between ${min} to ${max}</message>
</field-validator>
</field>
</validators>
4) Create struts.xml
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<
package name="default"
extends="struts-default">
<action name="register"
class="com.javaspot.Register">
<result name="input">index.jsp</result>
<result>welcome.jsp</result>
</action>
</
package>
</struts>
5) Create view component
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Date of Birth:<s:property value="dob"/>
int validation
The productId, employeeId can be used by int validator it can check given number is in specified range.
Parameters of int validator
| Parameter |
| fieldName |
| min |
| max |
double validation
Product price is used in double validation, it is in floating point of specified range.
Parameters of double validator
| Parameter |
| fieldName |
| minInclusive |
| maxInclusive |
| minExclusive |
| maxExclusive |
Example:
<validators>
<!-- Plain Validator Syntax -->
<validator type="double"
>
<param name="fieldName"
>price
</param>
<param name="minInclusive"
>100.0
</param>
<param name="maxInclusive"
>10000.0
</param>
<message>Price must be between ${minInclusive} and ${maxInclusive}
</message>
</validator>
</validators>
<validators>
<!-- Field Validator Syntax -->
<field name="price"
>
<field-validator type="double"
>
<param name="minInclusive"
>100.0
</param>
<param name="maxInclusive"
>10000.0
</param>
<message>Price must be between ${minInclusive} and ${maxInclusive}
</message>
</field-validator>
</field>
</validators>
url validation
It is used in website url ,reciprocal links, it checks the value is in string with valid url.
Parameters of url validator
| Parameter |
Description |
| fieldName |
specifies the field name that is to be validated. It is required in Plain-Validator only. |
Example of url validator
<validators>
<!-- Plain Validator Syntax -->
<validator type="url"
>
<param name="fieldName"
>website
</param>
<message>Invalid website url
</message>
</validator>
</validators>
<validators>
<!-- Field Validator Syntax -->
<field-validator type="url"
>
<field name="website"
>
<message>Invalid website url
</message>
</field>
</field-validator>
</validators>
Regex Validation
Password and security key can be used in Regex Validation,the given string with regular expression.
Parameters of regex validator
| Parameter |
| fieldName |
| expression |
| caseSensitive |
| trim |
Example of regex validator
<validators>
<!-- Plain Validator Syntax -->
<validator type="regex"
>
<param name="fieldName"
>data
</param>
<param name="expression"
>[A-Z,a-z,0-9]{5}
</param>
<message>data must be alpha numeric of 5 digits
</message>
</validator>
</validators>
<validators>
<!-- Field Validator Syntax -->
<field name="data"
>
<field-validator type="regex"
>
<param name="expression"
>[A-Z,a-z,0-9]{5}
</param>
<message>data must be alpha numeric of 5 digits
</message>
</field-validator>
</field>
</validators>