Struts 2 E-mail Validator
The email validator in Struts 2 Framework checks
whether a
given String field is empty or not and contains a valid email address or not. If the entered value
does not
match with the email type then the e-mail validator generates an error message.
The error message is supplied
between the <message> </message> tag. The following example demonstrates
how to use an email validator to check the entered value.
Follow the steps to develop the email validator example:
Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here --> <!-- Email validation --> <action name="emailValidation"> <result>/pages/emailInputForm.jsp</result> </action> <action name="emailValidation1" class="net.roseindia.EmailVaLidationAction"> <result name="input">/pages/emailInputForm.jsp</result> <result name="error">/pages/emailInputForm.jsp</result> <result>/pages/emailSuccess.jsp</result> </action> <!-- Add actions here --> </package> <!-- Add packages here --> </struts> |
Step 2 : Create an input jsp form. as shown below:
emailInputForm.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
|
Step 3 : Create an Action class.
EmailVaLidationAction.java
package net.roseindia;
|
Step 4 : Create an e-mail validator as:.
The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.
email validator :
This Field Validator
checks whether a given String field is empty or not and contains a valid email address or
not. If it has valid email type then the user is sent to the emailSuccess.jsp
page. Otherwise, it displays the message given in the xml file (e.g. Please enter
a valid email.).
The email validator
takes the following parameters:
- fieldName - This is the field name of validator that validates. It is required only if the user is using Plain-Validator Syntax .
EmailVaLidationAction-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
|
When the correct email address is entered then the user gets the emailSuccess.jsp page
emailSuccess.jsp
<%@page language="java" %>
|
Output:
When this application executes the user gets the following output :
If you enter the wrong email address then you get a message as shown:
Again, If you enter the wrong email address then you get:
Again, If you enter the wrong email address then you get:
If you enter the correct email address:
Then you get: