You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Francisco Antonio Vieira Souza <av...@yahoo.com.br> on 2005/09/20 20:48:16 UTC

Help - I cannot validate a simple form with 2 fields

Hi all,

I really need a big help in validation with Struts, I dont know why but 
I just cant validate a very simple form I have, with 2 simple fields 
(login and password), I have follown all tutorials I got but til now no 
success.

I am not able to validate either in server side or client side.

I am using Struts 1.2.7 - Is there any big difference in validating with 
this version and the previous ones?

Here are the stpeds I did:

1) created the DynaValidatorForm in struts-config and mapped the Actions 
it there too.
//-------------------------------------------------------------------------------------
....
<form-beans>
       <form-bean name="loginForm" 
type="org.apache.struts.validator.DynaValidatorForm">
           <form-property name="login" type="java.lang.String" />
           <form-property name="senha" type="java.lang.String" />
           <form-property name="senha2" type="java.lang.String" />
       </form-bean>
   </form-beans>
....
<!-- this one is called to show the page with the fields -->
<action path="/prepararLogin"
           type="br.com.gerente.SuccessAction">
           <forward name="success" path="/paginas/login.jsp"/>
</action>

<!-- this one is processed when the submit button is pressed -->
<action path="/Login"
           type="br.com.gerente.ProcessaLoginDynaAction"
           name="loginForm"
           scope="request"
           input="input"
           validate="true">
           <forward name="success" path="/paginas/clienteCadastro.jsp"/>
           <forward name="input" path="/prepararLogin.do" />
</action>
...
<message-resources parameter="br/com/gerente/Resources"/>   ...
   <!-- ========================= Validator plugin 
================================= -->
   <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
       <set-property
       property="pathnames"
       value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
       <set-property property="stopOnFirstError" value="true" />
   </plug-in>

2) create the action to call the login.jsp (and others): SuccessAction.java
//-------------------------------------------------------------------------------------
package br.com.gerente;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class SuccessAction extends Action {
     /** Creates a new instance of SuccessAction */
   public SuccessAction() {
       super();
   }
     /**
    * Returns the <code>ActionForward</code> named "success" if one is
    * configured or <code>null</code>if it cannot be found.
    *
    * Searches first for a local forward, then a global forward.
    *
    * @param mapping The ActionMapping used to select this instance
    * @param form The optional ActionForm bean for this request (if any)
    * @param request The HTTP request we are processing
    * @param response The HTTP response we are creating
    *
    * @exception Exception if mapping.findForward throws an Exception
    *
    * @return the "success" ActionForward, or null if it cannot be found
    */
   public ActionForward execute(
           ActionMapping mapping,
           ActionForm form,
           HttpServletRequest request,
           HttpServletResponse response)
           throws Exception {
             return mapping.findForward("success");
         }
}

3) created the action: ProcessaLoginDynaAction.java
package br.com.gerente;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;

public class ProcessaLoginDynaAction extends Action {
     /** Creates a new instance of ProcessaLoginDynaAction */
   public ProcessaLoginDynaAction() {
       super();
   }
     /**
    * Process the request and return an <code>ActionForward</code> instance
    * describing where and how control should be forwarded, or
    * <code>null</code>if the response has already been completed.
    *
    * @param mapping The ActionMapping used to select this instance
    * @param form The optional ActionForm bean for this request (if any)
    * @param request The HTTP request we are processing
    * @param response The HTTP response we are creating
    *
    * @exception Exception if the application logic throws an exception
    *
    * @return the ActionForward for the next view
    */
   public ActionForward execute(
           ActionMapping mapping,
           ActionForm form,
           HttpServletRequest request,
           HttpServletResponse response)
           throws Exception {
             // Se o usuario pressionar o botao 'Cancelar' volta para o 
inicio
       if (isCancelled(request)) {
           return mapping.findForward("inicio");
       }
       DynaValidatorForm dynaForm = (DynaValidatorForm)form;
       //dynaForm.set("login","nome do login");
       //System.out.println("Login: "+dynaForm.get("login") );
       // Forward to result page
       return mapping.findForward("success");
   } }

4) created login.jsp:
//-------------------------------------------------------------------------------------
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" 
prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" 
prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
prefix="logic" %>

<html:html locale="true">
   <head>
       <title><bean:message key="login.titulo"/></title>
       <html:base/>
       <link rel="stylesheet" type="text/css" href="estilo.css" />
   </head>
   <body>
       <center>
           <h1><bean:message key="login.titulo"/></h1>
                     <html:errors property="login"/>
                         <table border="0" width="50%">
               <html:form action="/Login.do" focus="login" method="post" 
onsubmit="return validateformLogin(this)">
                   <thead>
                       <tr>
                           <th></th>
                           <th></th>
                       </tr>
                   </thead>
                   <tbody>
                       <tr>
                           <td class="into"><bean:message 
key="login.nome"/></td>
                           <td>
                               <html:text property="login" size="20" 
maxlength="20" />
                           </td>
                       </tr>
                       <tr>
                           <td><bean:message key="login.senha"/></td>
                           <td><html:password property="senha" size="20" 
maxlength="10"/></td>
                       </tr>
                       <tr>
                           <td></td>
                           <td>
                               <html:submit>
                                   <bean:message key="botao.enviar" />
                               </html:submit>
                               <html:cancel>
                                   <bean:message key="botao.cancelar" />
                               </html:cancel>
                           </td>
                       </tr>
                   </tbody>
               </html:form>
           </table>                              </center>          </body>
   <html:javascript formName="loginForm" dynamicJavascript="true" 
staticJavascript="false"/>
</html:html>

5) The resources file: Resources.properties
//-------------------------------------------------------------------------------------
#--- erro padrao --
errors.header=<font color="red">Erro! Por favor verifique a(s) 
seguinte(s) mensagem(ns):<ul>
errors.footer=</ul></font>
errors.prefix=<LI>
errors.suffix=</LI>

errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} é obrigatório.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
welcome.title=Struts Application
sistema.titulo=Sistema de Gerenciamento dos Clientes da Kooky
cliente.titulo.cadastro=Cadastro de Clientes
cliente.titulo.dados=Cadastro de Clientes - Dados
welcome.heading=Struts Applications in Netbeans!
welcome.message=It's easy to create Struts applications with NetBeans.

login.titulo=Login de Acesso ao Sistema [G]erente
login.nome=Nome de acesso
login.senha=Senha de acesso

erro.data=Data Invalida
erro.obrigatorio=Dados obrigatorio
erro.email=Email errado

# -- campos obrigatorios --
id.obrigatorio=O Indentificador é obrigatório

# -- formatando --
formato.data=dd/MM/yyyy
formato.moeda=R$ #.##0,00;R$ (#.##0,00)

# -- botoes --
botao.enviar=Enviar Dados
botao.cancelar=Cancelar
botao.confirmar=Confirmar
botao.limpar=Limpar
botao.salvar=Salvar

6) the validation.xml:
//-------------------------------------------------------------------------------------
<formset language="pt" country="BR" >

       <constant>
           <constant-name>postalCode</constant-name>
           <constant-value>^[0-9a-zA-Z]*$</constant-value>
       </constant>

       <form name="loginForm">
           <field property="login" depends="required">
               <arg key="login.nome"/>
           </field>
           <field property="senha" depends="required">
               <arg key="login.senha"/>
           </field>                 
       </form>
</formset>

//-------------------------------------------------------------------------------------
So, according to the mapping action when I press the submit button with 
the fileds empty it should show me 2 messages in the page, right? But it 
does not show anything, just call the next page.
What am I doing wrong?
I really would appreciate any help from you guys.

Thanks in advance.
Francisco.


	

	
		
_______________________________________________________ 
Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito mais. Instale agora! 
www.yahoo.com.br/messenger/

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Testing Struts Applicaton

Posted by Laurie Harper <la...@holoweb.net>.
Sorry, I meant a distribution of the current sources rather than sources 
for the last release. Try here:

http://svn.apache.org/builds/struts/maven/trunk/nightly/struts-taglib/

I don't know what's in the taglibs project will help you, but it does 
use Cactus so it might at least get you started.

L.

rahul wrote:
> hi Laurie,
> 
> I am trying to test my struts appplication, 
> first I tried MockStrutsTestCase but its not working because
> my database connections are coming via tomcat(I have placed my
> jconnect.jar file in tomcat_home/common/lib and configured my 
> application's context.xml file)
> 
> Therefore I am looking to use In-Container Testing
> 
> That's the reason I was asking for some sample CactusStrutsTestCase code
> 
> I also downloaded Struts-src from 
> http://apache.mirrors.redwire.net/struts/source/struts-1.2.7-src.zip
> 
> but didn't get any taglibs/test-cactus in it
> 
> 
>>-----Original Message-----
>>From: news [mailto:news@sea.gmane.org]On Behalf Of Laurie Harper
>>Sent: Friday, September 23, 2005 1:05 AM
>>To: user@struts.apache.org
>>Subject: Re: Testing Struts Applicaton
>>
>>
>>rahul wrote:
>>
>>>Can anyone post some sample CactusStrutsTestCase code
>>
>>That's a bit vague; what are you trying to test? One place you could 
>>look is the Cactus test suite for the taglibs subproject in the Struts 
>>source (grab a current source distribution or checkout from subversion, 
>>and look in taglibs/test-cactus).
>>
>>L.
>>
>>
>>---------------------------------------------------------------------
>>To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
>>For additional commands, e-mail: user-help@struts.apache.org
>>
>>


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


RE: Testing Struts Applicaton

Posted by rahul <ra...@amsoft.net>.
hi Laurie,

I am trying to test my struts appplication, 
first I tried MockStrutsTestCase but its not working because
my database connections are coming via tomcat(I have placed my
jconnect.jar file in tomcat_home/common/lib and configured my 
application's context.xml file)

Therefore I am looking to use In-Container Testing

That's the reason I was asking for some sample CactusStrutsTestCase code

I also downloaded Struts-src from 
http://apache.mirrors.redwire.net/struts/source/struts-1.2.7-src.zip

but didn't get any taglibs/test-cactus in it

> -----Original Message-----
> From: news [mailto:news@sea.gmane.org]On Behalf Of Laurie Harper
> Sent: Friday, September 23, 2005 1:05 AM
> To: user@struts.apache.org
> Subject: Re: Testing Struts Applicaton
> 
> 
> rahul wrote:
> > Can anyone post some sample CactusStrutsTestCase code
> 
> That's a bit vague; what are you trying to test? One place you could 
> look is the Cactus test suite for the taglibs subproject in the Struts 
> source (grab a current source distribution or checkout from subversion, 
> and look in taglibs/test-cactus).
> 
> L.
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
> 
> 


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Testing Struts Applicaton

Posted by Laurie Harper <la...@holoweb.net>.
rahul wrote:
> Can anyone post some sample CactusStrutsTestCase code

That's a bit vague; what are you trying to test? One place you could 
look is the Cactus test suite for the taglibs subproject in the Struts 
source (grab a current source distribution or checkout from subversion, 
and look in taglibs/test-cactus).

L.


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Francisco Antonio Vieira Souza <av...@yahoo.com.br>.
Alright thanks, you know what? I am giving up Struts,,,,
I dont understand why this stuff has to be so complicated and nobody in 
the whole world knows anything about it, I am Swing developer and I 
think I will keep that.

Thanks anyway

Laurie Harper escreveu:

> Erm, yes? You were complaining that validator wasn't being invoked 
> after you switched to sub-classing ActionForm directly / implementing 
> validate() yourself. I was just pointing out that it's not expected to 
> be in that case.
>
> L.
>
> Francisco Antonio Vieira Souza wrote:
>
>> Everything you said IS here.
>>
>> Laurie Harper escreveu:
>>
>>> If you are just using an ActionForm subclass you wrote, Validator 
>>> isn't used so the behaviour you're now seeing is correct. If you 
>>> want to use Validator, your ActionForm class needs to extend 
>>> ValidatorForm or ValidatorActionForm rather than ActionForm; if you 
>>> want to include a validate() method in that class, it should call 
>>> super.validate() to invoke the Validator-supplied validation.
>>>
>>> L.
>>>
>>> Francisco Antonio Vieira Souza wrote:
>>>
>>>> I really dont get it, I might be being so stupid not figuring out 
>>>> what is going on wrong here, but I dont.
>>>>
>>>> Clearing a little. I decided not to use DynaForm and go back to the 
>>>> usual ActionForm and gave up using Client-side validation.
>>>>
>>>> When I implement the validate method of the Bean (as it is now) I 
>>>> get the error messages as expected, but I had to create a protected 
>>>> method to check if the field was null or blank, then put the error 
>>>> message in the ActionMessage.
>>>>
>>>> But I dont see any sense in doing such thing like that, why should 
>>>> I do this inside validate method if I have already said in 
>>>> validation.xml that those fields are REQUIRED, at least that 
>>>> message should be shown to the user. Correct me if I am wrong.
>>>>
>>>> If I comment the validate method nothing happen, it is not able to 
>>>> check if the field was left blank.
>>>>
>>>> Please be pacience and have a look again:
>>>>
>>>> struts-config.xml:
>>>> <?xml version="1.0" encoding="ISO-8859-1" ?>
>>>>
>>>> <!DOCTYPE struts-config PUBLIC
>>>>          "-//Apache Software Foundation//DTD Struts Configuration 
>>>> 1.2//EN"
>>>>          
>>>> "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
>>>>
>>>>
>>>> <struts-config>
>>>>      <form-beans>
>>>>        <!-- This is it -->
>>>>        <form-bean name="LoginUsuarioForm" 
>>>> type="br.com.gerente.bean.LoginFormBean"/>
>>>>              <form-bean name="GetClienteForm" 
>>>> type="br.com.gerente.bean.GetClienteFormBean"/>          </form-beans>
>>>>      <global-exceptions>
>>>>      </global-exceptions>
>>>>
>>>>    <global-forwards>
>>>>        <forward name="welcome"  path="/Clientes.do"/>
>>>>        <forward name="inicio" path="/index.jsp" 
>>>> redirect="true"/>          </global-forwards>
>>>>
>>>>    <action-mappings>
>>>>        <!-- This is an action just to call the .jsp file with the 
>>>> form -->
>>>>        <action path="/prepararLogin"
>>>>            type="br.com.gerente.action.SuccessAction">
>>>>            <forward name="success" path="/paginas/login.jsp"/>
>>>>        </action>
>>>>              <!-- This is my (first) problem in validation -->
>>>>        <action name="LoginUsuarioForm"
>>>>            input="/paginas/login.jsp"
>>>>            path="/LoginUsuario"
>>>>            scope="request"
>>>>            type="br.com.gerente.action.LoginUsuarioAction"
>>>>            validate="true">
>>>>            <forward name="sucesso" 
>>>> path="/paginas/clienteCadastro.jsp"/>
>>>>        </action>
>>>>              <!-- This is just the next form to be processed after 
>>>> validating the previous -->
>>>>        <action path="/Clientes" 
>>>> forward="/paginas/clienteCadastro.jsp"/>
>>>>              <!-- This is another form with the data from the 
>>>> previous inputs -->
>>>>        <action name="GetClienteForm"
>>>>            input="/paginas/clienteCadastro.jsp"
>>>>            path="/clientes"
>>>>            scope="request"
>>>>            type="br.com.gerente.action.GetClienteFormAction">
>>>>            <forward name="mostrandoDadosCliente"
>>>>            path="/paginas/clienteDados.jsp"/>
>>>>        </action>
>>>>                  </action-mappings>
>>>>      <controller 
>>>> processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
>>>>    <message-resources parameter="br/com/gerente/Resources"/>        
>>>> <!-- ========================= Tiles plugin 
>>>> ===============================-->     <plug-in 
>>>> className="org.apache.struts.tiles.TilesPlugin" >
>>>>        <set-property property="definitions-config" 
>>>> value="/WEB-INF/tiles-defs.xml" />            <set-property 
>>>> property="moduleAware" value="true" />
>>>>    </plug-in>
>>>>      <!-- ========================= Validator plugin 
>>>> ================================= -->
>>>>    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>>>>        <set-property
>>>>        property="pathnames"
>>>>        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>>>>        <set-property property="stopOnFirstError" value="true" />
>>>>    </plug-in>
>>>>
>>>> </struts-config>
>>>>
>>>> validation.xml:
>>>> <?xml version="1.0" encoding="ISO-8859-1" ?>
>>>>
>>>> <!DOCTYPE form-validation PUBLIC
>>>>          "-//Apache Software Foundation//DTD Commons Validator 
>>>> Rules Configuration 1.1.3//EN"
>>>>          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
>>>>
>>>> <form-validation>
>>>>
>>>>    <global>
>>>>    </global>
>>>>      <formset >
>>>>        <constant>
>>>>            <constant-name>postalCode</constant-name>
>>>>            <constant-value>^[0-9a-zA-Z]*$</constant-value>
>>>>        </constant>
>>>>
>>>>        <form name="LoginUsuarioForm">
>>>>            <field property="usuario" depends="required">
>>>>                <arg key="login.usuario"/>
>>>>            </field>
>>>>            <field property="senha" depends="required">
>>>>                <arg key="login.senha"/>
>>>>            </field>                  </form>          </formset>
>>>>
>>>> </form-validation>
>>>> //--------------------------------------------------------------------------------------------------------------- 
>>>>
>>>>
>>>> /*
>>>> * LoginFormBean.java
>>>> *
>>>> * Created on 21 de Setembro de 2005, 08:25
>>>> *
>>>> */
>>>>
>>>> package br.com.gerente.bean;
>>>>
>>>> import javax.servlet.http.HttpServletRequest;
>>>> import org.apache.struts.action.ActionMapping;
>>>> import org.apache.struts.action.ActionErrors;
>>>> import org.apache.struts.action.ActionMessage;
>>>>
>>>> public class LoginFormBean extends 
>>>> org.apache.struts.validator.ValidatorForm {
>>>>    private String usuario;
>>>>    private String senha;
>>>>    private String senhaConfirmada;
>>>>      public LoginFormBean() {
>>>>    }
>>>>      public void reset(ActionMapping actionMapping, 
>>>> HttpServletRequest request) {
>>>>    }
>>>>
>>>>    public ActionErrors validate(ActionMapping actionMapping, 
>>>> HttpServletRequest request) {
>>>>        ActionErrors errors = super.validate( actionMapping, request );
>>>>        if (errors == null) {
>>>>            errors = new ActionErrors(  );
>>>>        }
>>>>        if( nullOrBlank( (String)this.getUsuario()) ) {
>>>>            errors.add("usuario", new 
>>>> ActionMessage("login.usuario.requerido"));
>>>>        }
>>>>        if( nullOrBlank( (String)this.getSenha()) ) {
>>>>            errors.add("senha", new 
>>>> ActionMessage("login.senha.requerido"));
>>>>        }
>>>>              return errors;
>>>>    }
>>>>      protected boolean nullOrBlank(String str) {
>>>>        return ((str == null) || (str.length() == 0));
>>>>    }
>>>>      public String getUsuario() {
>>>>        return usuario;
>>>>    }
>>>>      public void setUsuario(String usuario) {
>>>>        this.usuario = usuario;
>>>>    }
>>>>      public String getSenha() {
>>>>        return senha;
>>>>    }
>>>>      public void setSenha(String senha) {
>>>>        this.senha = senha;
>>>>    }
>>>>      public String getSenhaConfirmada() {
>>>>        return senhaConfirmada;
>>>>    }
>>>>      public void setSenhaConfirmada(String senhaConfirmada) {
>>>>        this.senhaConfirmada = senhaConfirmada;
>>>>    }
>>>>   }
>>>> //--------------------------------------------------------------------------------------------------------------- 
>>>>
>>>>
>>>> /*
>>>> * LoginUsuarioAction.java
>>>> *
>>>> * Created on 21 de Setembro de 2005, 09:50
>>>> *
>>>> */
>>>>
>>>> package br.com.gerente.action;
>>>>
>>>> import br.com.gerente.bean.GetClienteFormBean;
>>>> import javax.servlet.http.HttpServletRequest;
>>>> import javax.servlet.http.HttpServletResponse;
>>>>
>>>> import org.apache.struts.action.ActionForm;
>>>> import org.apache.struts.action.ActionForward;
>>>> import org.apache.struts.action.ActionMapping;
>>>>
>>>> public class LoginUsuarioAction extends 
>>>> org.apache.struts.action.Action {
>>>>      /** Creates a new instance of LoginUsuarioAction */
>>>>    public LoginUsuarioAction() {
>>>>    }
>>>>      public ActionForward execute(ActionMapping mapping, ActionForm 
>>>> form, HttpServletRequest request, HttpServletResponse response) 
>>>> throws Exception {
>>>>        return mapping.findForward("sucesso");
>>>>    }
>>>> }
>>>> //--------------------------------------------------------------------------------------------------------------- 
>>>>
>>>>
>>>> Resources.properties:
>>>> #--- erro padrao / default errors --
>>>> errors.header=<font color="red">Erro! Por favor verifique a(s) 
>>>> seguinte(s) mensagem(ns):<ul>
>>>> errors.footer=</ul></font>
>>>> errors.prefix=<LI>
>>>> errors.suffix=</LI>
>>>>
>>>> errors.invalid={0} is invalid.
>>>> errors.maxlength={0} can not be greater than {1} characters.
>>>> errors.minlength={0} can not be less than {1} characters.
>>>> errors.range={0} is not in the range {1} through {2}.
>>>> errors.required={0} é obrigatório.
>>>> errors.byte={0} must be an byte.
>>>> errors.date={0} is not a date.
>>>> errors.double={0} must be an double.
>>>> errors.float={0} must be an float.
>>>> errors.integer={0} must be an integer.
>>>> errors.long={0} must be an long.
>>>> errors.short={0} must be an short.
>>>> errors.creditcard={0} is not a valid credit card number.
>>>> errors.email={0} is an invalid e-mail address.
>>>> errors.cancel=Operation cancelled.
>>>> errors.detail={0}
>>>> errors.general=The process did not complete. Details should follow.
>>>> errors.token=Request could not be completed. Operation is not in 
>>>> sequence.
>>>>
>>>> login.titulo=Login de Acesso ao Sistema [G]erente
>>>> login.usuario=Nome de acesso
>>>> login.senha=Senha de acesso
>>>> login.usuario.requerido=Nome de acesso obrigatório
>>>> login.senha.requerido=Senha de acesso obrigatório
>>>>
>>>> # -- botoes/buttons --
>>>> botao.enviar=Enviar Dados
>>>> botao.cancelar=Cancelar
>>>> botao.confirmar=Confirmar
>>>> botao.limpar=Limpar
>>>> botao.salvar=Salvar
>>>> //--------------------------------------------------------------------------------------------------------------- 
>>>>
>>>>
>>>> login.jsp:
>>>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" 
>>>> prefix="bean" %>
>>>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" 
>>>> prefix="html" %>
>>>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
>>>> prefix="logic" %>
>>>>
>>>> <html:html locale="true">
>>>>    <head>
>>>>        <title><bean:message key="login.titulo"/></title>
>>>>        <html:base/>          </head>
>>>>      <body>
>>>>        <center>
>>>>            <h1><bean:message key="login.titulo"/></h1>
>>>>                      <table width="50%">
>>>>                <html:form action="/LoginUsuario.do" focus="login" 
>>>> method="post">
>>>>                    <thead>
>>>>                        <tr>
>>>>                            <th ><bean:message 
>>>> key="login.usuario"/></th>
>>>>                            <th ><bean:message key="login.senha"/></th>
>>>>                        </tr>
>>>>                    </thead>
>>>>                    <tbody>
>>>>                        <tr>
>>>>                            <td><html:text property="usuario" 
>>>> size="20" maxlength="20" /></td>
>>>>                            <td><html:password property="senha" 
>>>> size="20" 
>>>> maxlength="10"/></td>                                              
>>>> </tr>
>>>>                        <tr>
>>>>                            <td>
>>>>                                <html:submit>
>>>>                                    <bean:message key="botao.enviar" />
>>>>                                </html:submit>
>>>>                            </td>
>>>>                            <td>
>>>>                                <html:cancel>
>>>>                                    <bean:message 
>>>> key="botao.cancelar" />
>>>>                                </html:cancel>
>>>>                            </td>
>>>>                        </tr>
>>>>                    </tbody>
>>>>                </html:form>
>>>>            </table>                              </center>
>>>>        <html:errors />
>>>>    </body>
>>>>    <html:javascript formName="LoginUsuarioForm" 
>>>> dynamicJavascript="true" staticJavascript="false"/>
>>>>
>>>> </html:html>
>>>>
>>>> Thanks in advance.
>>>> Francisco
>>>>
>>>>               
>>>> _______________________________________________________ Novo Yahoo! 
>>>> Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e 
>>>> muito mais. Instale agora! www.yahoo.com.br/messenger/
>>>
>>>
>>>
>>>
>>>
>>> ---------------------------------------------------------------------
>>> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
>>> For additional commands, e-mail: user-help@struts.apache.org
>>>
>>>
>>
>>    
>>            _______________________________________________________ 
>> Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos 
>> emoticons e muito mais. Instale agora! www.yahoo.com.br/messenger/
>
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
>
>

	

	
		
_______________________________________________________ 
Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito mais. Instale agora! 
www.yahoo.com.br/messenger/

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Laurie Harper <la...@holoweb.net>.
Erm, yes? You were complaining that validator wasn't being invoked after 
you switched to sub-classing ActionForm directly / implementing 
validate() yourself. I was just pointing out that it's not expected to 
be in that case.

L.

Francisco Antonio Vieira Souza wrote:
> Everything you said IS here.
> 
> Laurie Harper escreveu:
> 
>> If you are just using an ActionForm subclass you wrote, Validator 
>> isn't used so the behaviour you're now seeing is correct. If you want 
>> to use Validator, your ActionForm class needs to extend ValidatorForm 
>> or ValidatorActionForm rather than ActionForm; if you want to include 
>> a validate() method in that class, it should call super.validate() to 
>> invoke the Validator-supplied validation.
>>
>> L.
>>
>> Francisco Antonio Vieira Souza wrote:
>>
>>> I really dont get it, I might be being so stupid not figuring out 
>>> what is going on wrong here, but I dont.
>>>
>>> Clearing a little. I decided not to use DynaForm and go back to the 
>>> usual ActionForm and gave up using Client-side validation.
>>>
>>> When I implement the validate method of the Bean (as it is now) I get 
>>> the error messages as expected, but I had to create a protected 
>>> method to check if the field was null or blank, then put the error 
>>> message in the ActionMessage.
>>>
>>> But I dont see any sense in doing such thing like that, why should I 
>>> do this inside validate method if I have already said in 
>>> validation.xml that those fields are REQUIRED, at least that message 
>>> should be shown to the user. Correct me if I am wrong.
>>>
>>> If I comment the validate method nothing happen, it is not able to 
>>> check if the field was left blank.
>>>
>>> Please be pacience and have a look again:
>>>
>>> struts-config.xml:
>>> <?xml version="1.0" encoding="ISO-8859-1" ?>
>>>
>>> <!DOCTYPE struts-config PUBLIC
>>>          "-//Apache Software Foundation//DTD Struts Configuration 
>>> 1.2//EN"
>>>          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
>>>
>>>
>>> <struts-config>
>>>      <form-beans>
>>>        <!-- This is it -->
>>>        <form-bean name="LoginUsuarioForm" 
>>> type="br.com.gerente.bean.LoginFormBean"/>
>>>              <form-bean name="GetClienteForm" 
>>> type="br.com.gerente.bean.GetClienteFormBean"/>          </form-beans>
>>>      <global-exceptions>
>>>      </global-exceptions>
>>>
>>>    <global-forwards>
>>>        <forward name="welcome"  path="/Clientes.do"/>
>>>        <forward name="inicio" path="/index.jsp" 
>>> redirect="true"/>          </global-forwards>
>>>
>>>    <action-mappings>
>>>        <!-- This is an action just to call the .jsp file with the 
>>> form -->
>>>        <action path="/prepararLogin"
>>>            type="br.com.gerente.action.SuccessAction">
>>>            <forward name="success" path="/paginas/login.jsp"/>
>>>        </action>
>>>              <!-- This is my (first) problem in validation -->
>>>        <action name="LoginUsuarioForm"
>>>            input="/paginas/login.jsp"
>>>            path="/LoginUsuario"
>>>            scope="request"
>>>            type="br.com.gerente.action.LoginUsuarioAction"
>>>            validate="true">
>>>            <forward name="sucesso" path="/paginas/clienteCadastro.jsp"/>
>>>        </action>
>>>              <!-- This is just the next form to be processed after 
>>> validating the previous -->
>>>        <action path="/Clientes" forward="/paginas/clienteCadastro.jsp"/>
>>>              <!-- This is another form with the data from the 
>>> previous inputs -->
>>>        <action name="GetClienteForm"
>>>            input="/paginas/clienteCadastro.jsp"
>>>            path="/clientes"
>>>            scope="request"
>>>            type="br.com.gerente.action.GetClienteFormAction">
>>>            <forward name="mostrandoDadosCliente"
>>>            path="/paginas/clienteDados.jsp"/>
>>>        </action>
>>>                  </action-mappings>
>>>      <controller 
>>> processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
>>>    <message-resources parameter="br/com/gerente/Resources"/>        
>>> <!-- ========================= Tiles plugin 
>>> ===============================-->     <plug-in 
>>> className="org.apache.struts.tiles.TilesPlugin" >
>>>        <set-property property="definitions-config" 
>>> value="/WEB-INF/tiles-defs.xml" />            <set-property 
>>> property="moduleAware" value="true" />
>>>    </plug-in>
>>>      <!-- ========================= Validator plugin 
>>> ================================= -->
>>>    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>>>        <set-property
>>>        property="pathnames"
>>>        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>>>        <set-property property="stopOnFirstError" value="true" />
>>>    </plug-in>
>>>
>>> </struts-config>
>>>
>>> validation.xml:
>>> <?xml version="1.0" encoding="ISO-8859-1" ?>
>>>
>>> <!DOCTYPE form-validation PUBLIC
>>>          "-//Apache Software Foundation//DTD Commons Validator Rules 
>>> Configuration 1.1.3//EN"
>>>          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
>>>
>>> <form-validation>
>>>
>>>    <global>
>>>    </global>
>>>      <formset >
>>>        <constant>
>>>            <constant-name>postalCode</constant-name>
>>>            <constant-value>^[0-9a-zA-Z]*$</constant-value>
>>>        </constant>
>>>
>>>        <form name="LoginUsuarioForm">
>>>            <field property="usuario" depends="required">
>>>                <arg key="login.usuario"/>
>>>            </field>
>>>            <field property="senha" depends="required">
>>>                <arg key="login.senha"/>
>>>            </field>                  </form>          </formset>
>>>
>>> </form-validation>
>>> //--------------------------------------------------------------------------------------------------------------- 
>>>
>>>
>>> /*
>>> * LoginFormBean.java
>>> *
>>> * Created on 21 de Setembro de 2005, 08:25
>>> *
>>> */
>>>
>>> package br.com.gerente.bean;
>>>
>>> import javax.servlet.http.HttpServletRequest;
>>> import org.apache.struts.action.ActionMapping;
>>> import org.apache.struts.action.ActionErrors;
>>> import org.apache.struts.action.ActionMessage;
>>>
>>> public class LoginFormBean extends 
>>> org.apache.struts.validator.ValidatorForm {
>>>    private String usuario;
>>>    private String senha;
>>>    private String senhaConfirmada;
>>>      public LoginFormBean() {
>>>    }
>>>      public void reset(ActionMapping actionMapping, 
>>> HttpServletRequest request) {
>>>    }
>>>
>>>    public ActionErrors validate(ActionMapping actionMapping, 
>>> HttpServletRequest request) {
>>>        ActionErrors errors = super.validate( actionMapping, request );
>>>        if (errors == null) {
>>>            errors = new ActionErrors(  );
>>>        }
>>>        if( nullOrBlank( (String)this.getUsuario()) ) {
>>>            errors.add("usuario", new 
>>> ActionMessage("login.usuario.requerido"));
>>>        }
>>>        if( nullOrBlank( (String)this.getSenha()) ) {
>>>            errors.add("senha", new 
>>> ActionMessage("login.senha.requerido"));
>>>        }
>>>              return errors;
>>>    }
>>>      protected boolean nullOrBlank(String str) {
>>>        return ((str == null) || (str.length() == 0));
>>>    }
>>>      public String getUsuario() {
>>>        return usuario;
>>>    }
>>>      public void setUsuario(String usuario) {
>>>        this.usuario = usuario;
>>>    }
>>>      public String getSenha() {
>>>        return senha;
>>>    }
>>>      public void setSenha(String senha) {
>>>        this.senha = senha;
>>>    }
>>>      public String getSenhaConfirmada() {
>>>        return senhaConfirmada;
>>>    }
>>>      public void setSenhaConfirmada(String senhaConfirmada) {
>>>        this.senhaConfirmada = senhaConfirmada;
>>>    }
>>>   }
>>> //--------------------------------------------------------------------------------------------------------------- 
>>>
>>>
>>> /*
>>> * LoginUsuarioAction.java
>>> *
>>> * Created on 21 de Setembro de 2005, 09:50
>>> *
>>> */
>>>
>>> package br.com.gerente.action;
>>>
>>> import br.com.gerente.bean.GetClienteFormBean;
>>> import javax.servlet.http.HttpServletRequest;
>>> import javax.servlet.http.HttpServletResponse;
>>>
>>> import org.apache.struts.action.ActionForm;
>>> import org.apache.struts.action.ActionForward;
>>> import org.apache.struts.action.ActionMapping;
>>>
>>> public class LoginUsuarioAction extends 
>>> org.apache.struts.action.Action {
>>>      /** Creates a new instance of LoginUsuarioAction */
>>>    public LoginUsuarioAction() {
>>>    }
>>>      public ActionForward execute(ActionMapping mapping, ActionForm 
>>> form, HttpServletRequest request, HttpServletResponse response) 
>>> throws Exception {
>>>        return mapping.findForward("sucesso");
>>>    }
>>> }
>>> //--------------------------------------------------------------------------------------------------------------- 
>>>
>>>
>>> Resources.properties:
>>> #--- erro padrao / default errors --
>>> errors.header=<font color="red">Erro! Por favor verifique a(s) 
>>> seguinte(s) mensagem(ns):<ul>
>>> errors.footer=</ul></font>
>>> errors.prefix=<LI>
>>> errors.suffix=</LI>
>>>
>>> errors.invalid={0} is invalid.
>>> errors.maxlength={0} can not be greater than {1} characters.
>>> errors.minlength={0} can not be less than {1} characters.
>>> errors.range={0} is not in the range {1} through {2}.
>>> errors.required={0} é obrigatório.
>>> errors.byte={0} must be an byte.
>>> errors.date={0} is not a date.
>>> errors.double={0} must be an double.
>>> errors.float={0} must be an float.
>>> errors.integer={0} must be an integer.
>>> errors.long={0} must be an long.
>>> errors.short={0} must be an short.
>>> errors.creditcard={0} is not a valid credit card number.
>>> errors.email={0} is an invalid e-mail address.
>>> errors.cancel=Operation cancelled.
>>> errors.detail={0}
>>> errors.general=The process did not complete. Details should follow.
>>> errors.token=Request could not be completed. Operation is not in 
>>> sequence.
>>>
>>> login.titulo=Login de Acesso ao Sistema [G]erente
>>> login.usuario=Nome de acesso
>>> login.senha=Senha de acesso
>>> login.usuario.requerido=Nome de acesso obrigatório
>>> login.senha.requerido=Senha de acesso obrigatório
>>>
>>> # -- botoes/buttons --
>>> botao.enviar=Enviar Dados
>>> botao.cancelar=Cancelar
>>> botao.confirmar=Confirmar
>>> botao.limpar=Limpar
>>> botao.salvar=Salvar
>>> //--------------------------------------------------------------------------------------------------------------- 
>>>
>>>
>>> login.jsp:
>>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" 
>>> prefix="bean" %>
>>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" 
>>> prefix="html" %>
>>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
>>> prefix="logic" %>
>>>
>>> <html:html locale="true">
>>>    <head>
>>>        <title><bean:message key="login.titulo"/></title>
>>>        <html:base/>          </head>
>>>      <body>
>>>        <center>
>>>            <h1><bean:message key="login.titulo"/></h1>
>>>                      <table width="50%">
>>>                <html:form action="/LoginUsuario.do" focus="login" 
>>> method="post">
>>>                    <thead>
>>>                        <tr>
>>>                            <th ><bean:message key="login.usuario"/></th>
>>>                            <th ><bean:message key="login.senha"/></th>
>>>                        </tr>
>>>                    </thead>
>>>                    <tbody>
>>>                        <tr>
>>>                            <td><html:text property="usuario" 
>>> size="20" maxlength="20" /></td>
>>>                            <td><html:password property="senha" 
>>> size="20" 
>>> maxlength="10"/></td>                                              </tr>
>>>                        <tr>
>>>                            <td>
>>>                                <html:submit>
>>>                                    <bean:message key="botao.enviar" />
>>>                                </html:submit>
>>>                            </td>
>>>                            <td>
>>>                                <html:cancel>
>>>                                    <bean:message key="botao.cancelar" />
>>>                                </html:cancel>
>>>                            </td>
>>>                        </tr>
>>>                    </tbody>
>>>                </html:form>
>>>            </table>                              </center>
>>>        <html:errors />
>>>    </body>
>>>    <html:javascript formName="LoginUsuarioForm" 
>>> dynamicJavascript="true" staticJavascript="false"/>
>>>
>>> </html:html>
>>>
>>> Thanks in advance.
>>> Francisco
>>>
>>>               _______________________________________________________ 
>>> Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos 
>>> emoticons e muito mais. Instale agora! www.yahoo.com.br/messenger/
>>
>>
>>
>>
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
>> For additional commands, e-mail: user-help@struts.apache.org
>>
>>
> 
>     
> 
>     
>        
> _______________________________________________________ Novo Yahoo! 
> Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito 
> mais. Instale agora! www.yahoo.com.br/messenger/


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Testing Struts Applicaton

Posted by rahul <ra...@amsoft.net>.
Hi All,

Can anyone post some sample CactusStrutsTestCase code


--RahulJoshi



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Francisco Antonio Vieira Souza <av...@yahoo.com.br>.
Everything you said IS here.

Laurie Harper escreveu:

> If you are just using an ActionForm subclass you wrote, Validator 
> isn't used so the behaviour you're now seeing is correct. If you want 
> to use Validator, your ActionForm class needs to extend ValidatorForm 
> or ValidatorActionForm rather than ActionForm; if you want to include 
> a validate() method in that class, it should call super.validate() to 
> invoke the Validator-supplied validation.
>
> L.
>
> Francisco Antonio Vieira Souza wrote:
>
>> I really dont get it, I might be being so stupid not figuring out 
>> what is going on wrong here, but I dont.
>>
>> Clearing a little. I decided not to use DynaForm and go back to the 
>> usual ActionForm and gave up using Client-side validation.
>>
>> When I implement the validate method of the Bean (as it is now) I get 
>> the error messages as expected, but I had to create a protected 
>> method to check if the field was null or blank, then put the error 
>> message in the ActionMessage.
>>
>> But I dont see any sense in doing such thing like that, why should I 
>> do this inside validate method if I have already said in 
>> validation.xml that those fields are REQUIRED, at least that message 
>> should be shown to the user. Correct me if I am wrong.
>>
>> If I comment the validate method nothing happen, it is not able to 
>> check if the field was left blank.
>>
>> Please be pacience and have a look again:
>>
>> struts-config.xml:
>> <?xml version="1.0" encoding="ISO-8859-1" ?>
>>
>> <!DOCTYPE struts-config PUBLIC
>>          "-//Apache Software Foundation//DTD Struts Configuration 
>> 1.2//EN"
>>          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
>>
>>
>> <struts-config>
>>      <form-beans>
>>        <!-- This is it -->
>>        <form-bean name="LoginUsuarioForm" 
>> type="br.com.gerente.bean.LoginFormBean"/>
>>              <form-bean name="GetClienteForm" 
>> type="br.com.gerente.bean.GetClienteFormBean"/>          </form-beans>
>>      <global-exceptions>
>>      </global-exceptions>
>>
>>    <global-forwards>
>>        <forward name="welcome"  path="/Clientes.do"/>
>>        <forward name="inicio" path="/index.jsp" 
>> redirect="true"/>          </global-forwards>
>>
>>    <action-mappings>
>>        <!-- This is an action just to call the .jsp file with the 
>> form -->
>>        <action path="/prepararLogin"
>>            type="br.com.gerente.action.SuccessAction">
>>            <forward name="success" path="/paginas/login.jsp"/>
>>        </action>
>>              <!-- This is my (first) problem in validation -->
>>        <action name="LoginUsuarioForm"
>>            input="/paginas/login.jsp"
>>            path="/LoginUsuario"
>>            scope="request"
>>            type="br.com.gerente.action.LoginUsuarioAction"
>>            validate="true">
>>            <forward name="sucesso" path="/paginas/clienteCadastro.jsp"/>
>>        </action>
>>              <!-- This is just the next form to be processed after 
>> validating the previous -->
>>        <action path="/Clientes" forward="/paginas/clienteCadastro.jsp"/>
>>              <!-- This is another form with the data from the 
>> previous inputs -->
>>        <action name="GetClienteForm"
>>            input="/paginas/clienteCadastro.jsp"
>>            path="/clientes"
>>            scope="request"
>>            type="br.com.gerente.action.GetClienteFormAction">
>>            <forward name="mostrandoDadosCliente"
>>            path="/paginas/clienteDados.jsp"/>
>>        </action>
>>                  </action-mappings>
>>      <controller 
>> processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
>>    <message-resources parameter="br/com/gerente/Resources"/>        
>> <!-- ========================= Tiles plugin 
>> ===============================-->     <plug-in 
>> className="org.apache.struts.tiles.TilesPlugin" >
>>        <set-property property="definitions-config" 
>> value="/WEB-INF/tiles-defs.xml" />            <set-property 
>> property="moduleAware" value="true" />
>>    </plug-in>
>>      <!-- ========================= Validator plugin 
>> ================================= -->
>>    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>>        <set-property
>>        property="pathnames"
>>        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>>        <set-property property="stopOnFirstError" value="true" />
>>    </plug-in>
>>
>> </struts-config>
>>
>> validation.xml:
>> <?xml version="1.0" encoding="ISO-8859-1" ?>
>>
>> <!DOCTYPE form-validation PUBLIC
>>          "-//Apache Software Foundation//DTD Commons Validator Rules 
>> Configuration 1.1.3//EN"
>>          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
>>
>> <form-validation>
>>
>>    <global>
>>    </global>
>>      <formset >
>>        <constant>
>>            <constant-name>postalCode</constant-name>
>>            <constant-value>^[0-9a-zA-Z]*$</constant-value>
>>        </constant>
>>
>>        <form name="LoginUsuarioForm">
>>            <field property="usuario" depends="required">
>>                <arg key="login.usuario"/>
>>            </field>
>>            <field property="senha" depends="required">
>>                <arg key="login.senha"/>
>>            </field>                  </form>          </formset>
>>
>> </form-validation>
>> //--------------------------------------------------------------------------------------------------------------- 
>>
>>
>> /*
>> * LoginFormBean.java
>> *
>> * Created on 21 de Setembro de 2005, 08:25
>> *
>> */
>>
>> package br.com.gerente.bean;
>>
>> import javax.servlet.http.HttpServletRequest;
>> import org.apache.struts.action.ActionMapping;
>> import org.apache.struts.action.ActionErrors;
>> import org.apache.struts.action.ActionMessage;
>>
>> public class LoginFormBean extends 
>> org.apache.struts.validator.ValidatorForm {
>>    private String usuario;
>>    private String senha;
>>    private String senhaConfirmada;
>>      public LoginFormBean() {
>>    }
>>      public void reset(ActionMapping actionMapping, 
>> HttpServletRequest request) {
>>    }
>>
>>    public ActionErrors validate(ActionMapping actionMapping, 
>> HttpServletRequest request) {
>>        ActionErrors errors = super.validate( actionMapping, request );
>>        if (errors == null) {
>>            errors = new ActionErrors(  );
>>        }
>>        if( nullOrBlank( (String)this.getUsuario()) ) {
>>            errors.add("usuario", new 
>> ActionMessage("login.usuario.requerido"));
>>        }
>>        if( nullOrBlank( (String)this.getSenha()) ) {
>>            errors.add("senha", new 
>> ActionMessage("login.senha.requerido"));
>>        }
>>              return errors;
>>    }
>>      protected boolean nullOrBlank(String str) {
>>        return ((str == null) || (str.length() == 0));
>>    }
>>      public String getUsuario() {
>>        return usuario;
>>    }
>>      public void setUsuario(String usuario) {
>>        this.usuario = usuario;
>>    }
>>      public String getSenha() {
>>        return senha;
>>    }
>>      public void setSenha(String senha) {
>>        this.senha = senha;
>>    }
>>      public String getSenhaConfirmada() {
>>        return senhaConfirmada;
>>    }
>>      public void setSenhaConfirmada(String senhaConfirmada) {
>>        this.senhaConfirmada = senhaConfirmada;
>>    }
>>   }
>> //--------------------------------------------------------------------------------------------------------------- 
>>
>>
>> /*
>> * LoginUsuarioAction.java
>> *
>> * Created on 21 de Setembro de 2005, 09:50
>> *
>> */
>>
>> package br.com.gerente.action;
>>
>> import br.com.gerente.bean.GetClienteFormBean;
>> import javax.servlet.http.HttpServletRequest;
>> import javax.servlet.http.HttpServletResponse;
>>
>> import org.apache.struts.action.ActionForm;
>> import org.apache.struts.action.ActionForward;
>> import org.apache.struts.action.ActionMapping;
>>
>> public class LoginUsuarioAction extends 
>> org.apache.struts.action.Action {
>>      /** Creates a new instance of LoginUsuarioAction */
>>    public LoginUsuarioAction() {
>>    }
>>      public ActionForward execute(ActionMapping mapping, ActionForm 
>> form, HttpServletRequest request, HttpServletResponse response) 
>> throws Exception {
>>        return mapping.findForward("sucesso");
>>    }
>> }
>> //--------------------------------------------------------------------------------------------------------------- 
>>
>>
>> Resources.properties:
>> #--- erro padrao / default errors --
>> errors.header=<font color="red">Erro! Por favor verifique a(s) 
>> seguinte(s) mensagem(ns):<ul>
>> errors.footer=</ul></font>
>> errors.prefix=<LI>
>> errors.suffix=</LI>
>>
>> errors.invalid={0} is invalid.
>> errors.maxlength={0} can not be greater than {1} characters.
>> errors.minlength={0} can not be less than {1} characters.
>> errors.range={0} is not in the range {1} through {2}.
>> errors.required={0} é obrigatório.
>> errors.byte={0} must be an byte.
>> errors.date={0} is not a date.
>> errors.double={0} must be an double.
>> errors.float={0} must be an float.
>> errors.integer={0} must be an integer.
>> errors.long={0} must be an long.
>> errors.short={0} must be an short.
>> errors.creditcard={0} is not a valid credit card number.
>> errors.email={0} is an invalid e-mail address.
>> errors.cancel=Operation cancelled.
>> errors.detail={0}
>> errors.general=The process did not complete. Details should follow.
>> errors.token=Request could not be completed. Operation is not in 
>> sequence.
>>
>> login.titulo=Login de Acesso ao Sistema [G]erente
>> login.usuario=Nome de acesso
>> login.senha=Senha de acesso
>> login.usuario.requerido=Nome de acesso obrigatório
>> login.senha.requerido=Senha de acesso obrigatório
>>
>> # -- botoes/buttons --
>> botao.enviar=Enviar Dados
>> botao.cancelar=Cancelar
>> botao.confirmar=Confirmar
>> botao.limpar=Limpar
>> botao.salvar=Salvar
>> //--------------------------------------------------------------------------------------------------------------- 
>>
>>
>> login.jsp:
>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" 
>> prefix="bean" %>
>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" 
>> prefix="html" %>
>> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
>> prefix="logic" %>
>>
>> <html:html locale="true">
>>    <head>
>>        <title><bean:message key="login.titulo"/></title>
>>        <html:base/>          </head>
>>      <body>
>>        <center>
>>            <h1><bean:message key="login.titulo"/></h1>
>>                      <table width="50%">
>>                <html:form action="/LoginUsuario.do" focus="login" 
>> method="post">
>>                    <thead>
>>                        <tr>
>>                            <th ><bean:message key="login.usuario"/></th>
>>                            <th ><bean:message key="login.senha"/></th>
>>                        </tr>
>>                    </thead>
>>                    <tbody>
>>                        <tr>
>>                            <td><html:text property="usuario" 
>> size="20" maxlength="20" /></td>
>>                            <td><html:password property="senha" 
>> size="20" 
>> maxlength="10"/></td>                                              </tr>
>>                        <tr>
>>                            <td>
>>                                <html:submit>
>>                                    <bean:message key="botao.enviar" />
>>                                </html:submit>
>>                            </td>
>>                            <td>
>>                                <html:cancel>
>>                                    <bean:message key="botao.cancelar" />
>>                                </html:cancel>
>>                            </td>
>>                        </tr>
>>                    </tbody>
>>                </html:form>
>>            </table>                              </center>
>>        <html:errors />
>>    </body>
>>    <html:javascript formName="LoginUsuarioForm" 
>> dynamicJavascript="true" staticJavascript="false"/>
>>
>> </html:html>
>>
>> Thanks in advance.
>> Francisco
>>
>>    
>>            _______________________________________________________ 
>> Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos 
>> emoticons e muito mais. Instale agora! www.yahoo.com.br/messenger/
>
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
>
>

	

	
		
_______________________________________________________ 
Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito mais. Instale agora! 
www.yahoo.com.br/messenger/

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Laurie Harper <la...@holoweb.net>.
If you are just using an ActionForm subclass you wrote, Validator isn't 
used so the behaviour you're now seeing is correct. If you want to use 
Validator, your ActionForm class needs to extend ValidatorForm or 
ValidatorActionForm rather than ActionForm; if you want to include a 
validate() method in that class, it should call super.validate() to 
invoke the Validator-supplied validation.

L.

Francisco Antonio Vieira Souza wrote:
> I really dont get it, I might be being so stupid not figuring out what 
> is going on wrong here, but I dont.
> 
> Clearing a little. I decided not to use DynaForm and go back to the 
> usual ActionForm and gave up using Client-side validation.
> 
> When I implement the validate method of the Bean (as it is now) I get 
> the error messages as expected, but I had to create a protected method 
> to check if the field was null or blank, then put the error message in 
> the ActionMessage.
> 
> But I dont see any sense in doing such thing like that, why should I do 
> this inside validate method if I have already said in validation.xml 
> that those fields are REQUIRED, at least that message should be shown to 
> the user. Correct me if I am wrong.
> 
> If I comment the validate method nothing happen, it is not able to check 
> if the field was left blank.
> 
> Please be pacience and have a look again:
> 
> struts-config.xml:
> <?xml version="1.0" encoding="ISO-8859-1" ?>
> 
> <!DOCTYPE struts-config PUBLIC
>          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
>          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
> 
> 
> <struts-config>
>      <form-beans>
>        <!-- This is it -->
>        <form-bean name="LoginUsuarioForm" 
> type="br.com.gerente.bean.LoginFormBean"/>
>              <form-bean name="GetClienteForm" 
> type="br.com.gerente.bean.GetClienteFormBean"/>          </form-beans>
>      <global-exceptions>
>      </global-exceptions>
> 
>    <global-forwards>
>        <forward name="welcome"  path="/Clientes.do"/>
>        <forward name="inicio" path="/index.jsp" redirect="true"/>       
>    </global-forwards>
> 
>    <action-mappings>
>        <!-- This is an action just to call the .jsp file with the form -->
>        <action path="/prepararLogin"
>            type="br.com.gerente.action.SuccessAction">
>            <forward name="success" path="/paginas/login.jsp"/>
>        </action>
>              <!-- This is my (first) problem in validation -->
>        <action name="LoginUsuarioForm"
>            input="/paginas/login.jsp"
>            path="/LoginUsuario"
>            scope="request"
>            type="br.com.gerente.action.LoginUsuarioAction"
>            validate="true">
>            <forward name="sucesso" path="/paginas/clienteCadastro.jsp"/>
>        </action>
>              <!-- This is just the next form to be processed after 
> validating the previous -->
>        <action path="/Clientes" forward="/paginas/clienteCadastro.jsp"/>
>              <!-- This is another form with the data from the previous 
> inputs -->
>        <action name="GetClienteForm"
>            input="/paginas/clienteCadastro.jsp"
>            path="/clientes"
>            scope="request"
>            type="br.com.gerente.action.GetClienteFormAction">
>            <forward name="mostrandoDadosCliente"
>            path="/paginas/clienteDados.jsp"/>
>        </action>
>                  </action-mappings>
>      <controller 
> processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
>    <message-resources parameter="br/com/gerente/Resources"/>        <!-- 
> ========================= Tiles plugin 
> ===============================-->     <plug-in 
> className="org.apache.struts.tiles.TilesPlugin" >
>        <set-property property="definitions-config" 
> value="/WEB-INF/tiles-defs.xml" />            <set-property 
> property="moduleAware" value="true" />
>    </plug-in>
>      <!-- ========================= Validator plugin 
> ================================= -->
>    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>        <set-property
>        property="pathnames"
>        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>        <set-property property="stopOnFirstError" value="true" />
>    </plug-in>
> 
> </struts-config>
> 
> validation.xml:
> <?xml version="1.0" encoding="ISO-8859-1" ?>
> 
> <!DOCTYPE form-validation PUBLIC
>          "-//Apache Software Foundation//DTD Commons Validator Rules 
> Configuration 1.1.3//EN"
>          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
> 
> <form-validation>
> 
>    <global>
>    </global>
>      <formset >
>        <constant>
>            <constant-name>postalCode</constant-name>
>            <constant-value>^[0-9a-zA-Z]*$</constant-value>
>        </constant>
> 
>        <form name="LoginUsuarioForm">
>            <field property="usuario" depends="required">
>                <arg key="login.usuario"/>
>            </field>
>            <field property="senha" depends="required">
>                <arg key="login.senha"/>
>            </field>                  </form>          </formset>
> 
> </form-validation>
> //--------------------------------------------------------------------------------------------------------------- 
> 
> 
> /*
> * LoginFormBean.java
> *
> * Created on 21 de Setembro de 2005, 08:25
> *
> */
> 
> package br.com.gerente.bean;
> 
> import javax.servlet.http.HttpServletRequest;
> import org.apache.struts.action.ActionMapping;
> import org.apache.struts.action.ActionErrors;
> import org.apache.struts.action.ActionMessage;
> 
> public class LoginFormBean extends 
> org.apache.struts.validator.ValidatorForm {
>    private String usuario;
>    private String senha;
>    private String senhaConfirmada;
>      public LoginFormBean() {
>    }
>      public void reset(ActionMapping actionMapping, HttpServletRequest 
> request) {
>    }
> 
>    public ActionErrors validate(ActionMapping actionMapping, 
> HttpServletRequest request) {
>        ActionErrors errors = super.validate( actionMapping, request );
>        if (errors == null) {
>            errors = new ActionErrors(  );
>        }
>        if( nullOrBlank( (String)this.getUsuario()) ) {
>            errors.add("usuario", new 
> ActionMessage("login.usuario.requerido"));
>        }
>        if( nullOrBlank( (String)this.getSenha()) ) {
>            errors.add("senha", new ActionMessage("login.senha.requerido"));
>        }
>              return errors;
>    }
>      protected boolean nullOrBlank(String str) {
>        return ((str == null) || (str.length() == 0));
>    }
>      public String getUsuario() {
>        return usuario;
>    }
>      public void setUsuario(String usuario) {
>        this.usuario = usuario;
>    }
>      public String getSenha() {
>        return senha;
>    }
>      public void setSenha(String senha) {
>        this.senha = senha;
>    }
>      public String getSenhaConfirmada() {
>        return senhaConfirmada;
>    }
>      public void setSenhaConfirmada(String senhaConfirmada) {
>        this.senhaConfirmada = senhaConfirmada;
>    }
>   }
> //--------------------------------------------------------------------------------------------------------------- 
> 
> 
> /*
> * LoginUsuarioAction.java
> *
> * Created on 21 de Setembro de 2005, 09:50
> *
> */
> 
> package br.com.gerente.action;
> 
> import br.com.gerente.bean.GetClienteFormBean;
> import javax.servlet.http.HttpServletRequest;
> import javax.servlet.http.HttpServletResponse;
> 
> import org.apache.struts.action.ActionForm;
> import org.apache.struts.action.ActionForward;
> import org.apache.struts.action.ActionMapping;
> 
> public class LoginUsuarioAction extends org.apache.struts.action.Action {
>      /** Creates a new instance of LoginUsuarioAction */
>    public LoginUsuarioAction() {
>    }
>      public ActionForward execute(ActionMapping mapping, ActionForm 
> form, HttpServletRequest request, HttpServletResponse response) throws 
> Exception {
>        return mapping.findForward("sucesso");
>    }
> }
> //--------------------------------------------------------------------------------------------------------------- 
> 
> 
> Resources.properties:
> #--- erro padrao / default errors --
> errors.header=<font color="red">Erro! Por favor verifique a(s) 
> seguinte(s) mensagem(ns):<ul>
> errors.footer=</ul></font>
> errors.prefix=<LI>
> errors.suffix=</LI>
> 
> errors.invalid={0} is invalid.
> errors.maxlength={0} can not be greater than {1} characters.
> errors.minlength={0} can not be less than {1} characters.
> errors.range={0} is not in the range {1} through {2}.
> errors.required={0} é obrigatório.
> errors.byte={0} must be an byte.
> errors.date={0} is not a date.
> errors.double={0} must be an double.
> errors.float={0} must be an float.
> errors.integer={0} must be an integer.
> errors.long={0} must be an long.
> errors.short={0} must be an short.
> errors.creditcard={0} is not a valid credit card number.
> errors.email={0} is an invalid e-mail address.
> errors.cancel=Operation cancelled.
> errors.detail={0}
> errors.general=The process did not complete. Details should follow.
> errors.token=Request could not be completed. Operation is not in sequence.
> 
> login.titulo=Login de Acesso ao Sistema [G]erente
> login.usuario=Nome de acesso
> login.senha=Senha de acesso
> login.usuario.requerido=Nome de acesso obrigatório
> login.senha.requerido=Senha de acesso obrigatório
> 
> # -- botoes/buttons --
> botao.enviar=Enviar Dados
> botao.cancelar=Cancelar
> botao.confirmar=Confirmar
> botao.limpar=Limpar
> botao.salvar=Salvar
> //--------------------------------------------------------------------------------------------------------------- 
> 
> 
> login.jsp:
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" 
> prefix="bean" %>
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" 
> prefix="html" %>
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
> prefix="logic" %>
> 
> <html:html locale="true">
>    <head>
>        <title><bean:message key="login.titulo"/></title>
>        <html:base/>          </head>
>      <body>
>        <center>
>            <h1><bean:message key="login.titulo"/></h1>
>                      <table width="50%">
>                <html:form action="/LoginUsuario.do" focus="login" 
> method="post">
>                    <thead>
>                        <tr>
>                            <th ><bean:message key="login.usuario"/></th>
>                            <th ><bean:message key="login.senha"/></th>
>                        </tr>
>                    </thead>
>                    <tbody>
>                        <tr>
>                            <td><html:text property="usuario" size="20" 
> maxlength="20" /></td>
>                            <td><html:password property="senha" size="20" 
> maxlength="10"/></td>                                              </tr>
>                        <tr>
>                            <td>
>                                <html:submit>
>                                    <bean:message key="botao.enviar" />
>                                </html:submit>
>                            </td>
>                            <td>
>                                <html:cancel>
>                                    <bean:message key="botao.cancelar" />
>                                </html:cancel>
>                            </td>
>                        </tr>
>                    </tbody>
>                </html:form>
>            </table>                              </center>
>        <html:errors />
>    </body>
>    <html:javascript formName="LoginUsuarioForm" dynamicJavascript="true" 
> staticJavascript="false"/>
> 
> </html:html>
> 
> Thanks in advance.
> Francisco
> 
>     
> 
>     
>        
> _______________________________________________________ Novo Yahoo! 
> Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito 
> mais. Instale agora! www.yahoo.com.br/messenger/


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Francisco Antonio Vieira Souza <av...@yahoo.com.br>.
ActionError(...) is deprecated in Struts 1.2.7

rahul escreveu:

>try this
> errors.add("usuario", new ActionError("login.usuario.requerido"));
>
>
>  
>
>>-----Original Message-----
>>From: Francisco Antonio Vieira Souza [mailto:avs1001@yahoo.com.br]
>>Sent: Wednesday, September 21, 2005 8:30 PM
>>To: Struts Users Mailing List
>>Subject: Re: Help - I cannot validate a simple form with 2 fields
>>
>>
>>I really dont get it, I might be being so stupid not figuring out what
>>is going on wrong here, but I dont.
>>
>>Clearing a little. I decided not to use DynaForm and go back to the
>>usual ActionForm and gave up using Client-side validation.
>>
>>When I implement the validate method of the Bean (as it is now) I get
>>the error messages as expected, but I had to create a protected method
>>to check if the field was null or blank, then put the error message in
>>the ActionMessage.
>>
>>But I dont see any sense in doing such thing like that, why should I do
>>this inside validate method if I have already said in validation.xml
>>that those fields are REQUIRED, at least that message should be shown to
>>the user. Correct me if I am wrong.
>>
>>If I comment the validate method nothing happen, it is not able to check
>>if the field was left blank.
>>
>>Please be pacience and have a look again:
>>
>>struts-config.xml:
>><?xml version="1.0" encoding="ISO-8859-1" ?>
>>
>><!DOCTYPE struts-config PUBLIC
>>          "-//Apache Software Foundation//DTD Struts
>>Configuration 1.2//EN"
>>          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
>>
>>
>><struts-config>
>>
>>    <form-beans>
>>        <!-- This is it -->
>>        <form-bean name="LoginUsuarioForm"
>>type="br.com.gerente.bean.LoginFormBean"/>
>>
>>        <form-bean name="GetClienteForm"
>>type="br.com.gerente.bean.GetClienteFormBean"/>
>>    </form-beans>
>>
>>    <global-exceptions>
>>
>>    </global-exceptions>
>>
>>    <global-forwards>
>>        <forward name="welcome"  path="/Clientes.do"/>
>>        <forward name="inicio" path="/index.jsp" redirect="true"/>
>>    </global-forwards>
>>
>>    <action-mappings>
>>        <!-- This is an action just to call the .jsp file with
>>the form -->
>>        <action path="/prepararLogin"
>>            type="br.com.gerente.action.SuccessAction">
>>            <forward name="success" path="/paginas/login.jsp"/>
>>        </action>
>>
>>        <!-- This is my (first) problem in validation -->
>>        <action name="LoginUsuarioForm"
>>            input="/paginas/login.jsp"
>>            path="/LoginUsuario"
>>            scope="request"
>>            type="br.com.gerente.action.LoginUsuarioAction"
>>            validate="true">
>>            <forward name="sucesso" path="/paginas/clienteCadastro.jsp"/>
>>        </action>
>>
>>        <!-- This is just the next form to be processed after validating
>>the previous -->
>>        <action path="/Clientes" forward="/paginas/clienteCadastro.jsp"/>
>>
>>        <!-- This is another form with the data from the previous
>>inputs -->
>>        <action name="GetClienteForm"
>>            input="/paginas/clienteCadastro.jsp"
>>            path="/clientes"
>>            scope="request"
>>            type="br.com.gerente.action.GetClienteFormAction">
>>            <forward name="mostrandoDadosCliente"
>>            path="/paginas/clienteDados.jsp"/>
>>        </action>
>>
>>    </action-mappings>
>>
>>    <controller
>>processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
>>    <message-resources parameter="br/com/gerente/Resources"/>
>>
>>    <!-- ========================= Tiles plugin
>>===============================-->
>>    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
>>        <set-property property="definitions-config"
>>value="/WEB-INF/tiles-defs.xml" />
>>        <set-property property="moduleAware" value="true" />
>>    </plug-in>
>>
>>    <!-- ========================= Validator plugin
>>================================= -->
>>    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>>        <set-property
>>        property="pathnames"
>>        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>>        <set-property property="stopOnFirstError" value="true" />
>>    </plug-in>
>>
>></struts-config>
>>
>>validation.xml:
>><?xml version="1.0" encoding="ISO-8859-1" ?>
>>
>><!DOCTYPE form-validation PUBLIC
>>          "-//Apache Software Foundation//DTD Commons Validator Rules
>>Configuration 1.1.3//EN"
>>          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
>>
>><form-validation>
>>
>>    <global>
>>    </global>
>>
>>    <formset >
>>        <constant>
>>            <constant-name>postalCode</constant-name>
>>            <constant-value>^[0-9a-zA-Z]*$</constant-value>
>>        </constant>
>>
>>        <form name="LoginUsuarioForm">
>>            <field property="usuario" depends="required">
>>                <arg key="login.usuario"/>
>>            </field>
>>            <field property="senha" depends="required">
>>                <arg key="login.senha"/>
>>            </field>
>>        </form>
>>    </formset>
>>
>></form-validation>
>>//----------------------------------------------------------------
>>-----------------------------------------------
>>
>>/*
>> * LoginFormBean.java
>> *
>> * Created on 21 de Setembro de 2005, 08:25
>> *
>>*/
>>
>>package br.com.gerente.bean;
>>
>>import javax.servlet.http.HttpServletRequest;
>>import org.apache.struts.action.ActionMapping;
>>import org.apache.struts.action.ActionErrors;
>>import org.apache.struts.action.ActionMessage;
>>
>>public class LoginFormBean extends
>>org.apache.struts.validator.ValidatorForm {
>>    private String usuario;
>>    private String senha;
>>    private String senhaConfirmada;
>>
>>    public LoginFormBean() {
>>    }
>>
>>    public void reset(ActionMapping actionMapping, HttpServletRequest
>>request) {
>>    }
>>
>>    public ActionErrors validate(ActionMapping actionMapping,
>>HttpServletRequest request) {
>>        ActionErrors errors = super.validate( actionMapping, request );
>>        if (errors == null) {
>>            errors = new ActionErrors(  );
>>        }
>>        if( nullOrBlank( (String)this.getUsuario()) ) {
>>            errors.add("usuario", new
>>ActionMessage("login.usuario.requerido"));
>>        }
>>        if( nullOrBlank( (String)this.getSenha()) ) {
>>            errors.add("senha", new
>>ActionMessage("login.senha.requerido"));
>>        }
>>
>>        return errors;
>>    }
>>
>>    protected boolean nullOrBlank(String str) {
>>        return ((str == null) || (str.length() == 0));
>>    }
>>
>>    public String getUsuario() {
>>        return usuario;
>>    }
>>
>>    public void setUsuario(String usuario) {
>>        this.usuario = usuario;
>>    }
>>
>>    public String getSenha() {
>>        return senha;
>>    }
>>
>>    public void setSenha(String senha) {
>>        this.senha = senha;
>>    }
>>
>>    public String getSenhaConfirmada() {
>>        return senhaConfirmada;
>>    }
>>
>>    public void setSenhaConfirmada(String senhaConfirmada) {
>>        this.senhaConfirmada = senhaConfirmada;
>>    }
>>
>>}
>>//----------------------------------------------------------------
>>-----------------------------------------------
>>
>>/*
>> * LoginUsuarioAction.java
>> *
>> * Created on 21 de Setembro de 2005, 09:50
>> *
>> */
>>
>>package br.com.gerente.action;
>>
>>import br.com.gerente.bean.GetClienteFormBean;
>>import javax.servlet.http.HttpServletRequest;
>>import javax.servlet.http.HttpServletResponse;
>>
>>import org.apache.struts.action.ActionForm;
>>import org.apache.struts.action.ActionForward;
>>import org.apache.struts.action.ActionMapping;
>>
>>public class LoginUsuarioAction extends org.apache.struts.action.Action {
>>
>>    /** Creates a new instance of LoginUsuarioAction */
>>    public LoginUsuarioAction() {
>>    }
>>
>>    public ActionForward execute(ActionMapping mapping, ActionForm form,
>>HttpServletRequest request, HttpServletResponse response) throws
>>Exception {
>>        return mapping.findForward("sucesso");
>>    }
>>}
>>//----------------------------------------------------------------
>>-----------------------------------------------
>>
>>Resources.properties:
>>#--- erro padrao / default errors --
>>errors.header=<font color="red">Erro! Por favor verifique a(s)
>>seguinte(s) mensagem(ns):<ul>
>>errors.footer=</ul></font>
>>errors.prefix=<LI>
>>errors.suffix=</LI>
>>
>>errors.invalid={0} is invalid.
>>errors.maxlength={0} can not be greater than {1} characters.
>>errors.minlength={0} can not be less than {1} characters.
>>errors.range={0} is not in the range {1} through {2}.
>>errors.required={0} é obrigatório.
>>errors.byte={0} must be an byte.
>>errors.date={0} is not a date.
>>errors.double={0} must be an double.
>>errors.float={0} must be an float.
>>errors.integer={0} must be an integer.
>>errors.long={0} must be an long.
>>errors.short={0} must be an short.
>>errors.creditcard={0} is not a valid credit card number.
>>errors.email={0} is an invalid e-mail address.
>>errors.cancel=Operation cancelled.
>>errors.detail={0}
>>errors.general=The process did not complete. Details should follow.
>>errors.token=Request could not be completed. Operation is not in sequence.
>>
>>login.titulo=Login de Acesso ao Sistema [G]erente
>>login.usuario=Nome de acesso
>>login.senha=Senha de acesso
>>login.usuario.requerido=Nome de acesso obrigatório
>>login.senha.requerido=Senha de acesso obrigatório
>>
>># -- botoes/buttons --
>>botao.enviar=Enviar Dados
>>botao.cancelar=Cancelar
>>botao.confirmar=Confirmar
>>botao.limpar=Limpar
>>botao.salvar=Salvar
>>//----------------------------------------------------------------
>>-----------------------------------------------
>>
>>login.jsp:
>><%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
>>prefix="bean" %>
>><%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
>>prefix="html" %>
>><%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
>>prefix="logic" %>
>>
>><html:html locale="true">
>>    <head>
>>        <title><bean:message key="login.titulo"/></title>
>>        <html:base/>
>>    </head>
>>
>>    <body>
>>        <center>
>>            <h1><bean:message key="login.titulo"/></h1>
>>
>>            <table width="50%">
>>                <html:form action="/LoginUsuario.do" focus="login"
>>method="post">
>>                    <thead>
>>                        <tr>
>>                            <th ><bean:message key="login.usuario"/></th>
>>                            <th ><bean:message key="login.senha"/></th>
>>                        </tr>
>>                    </thead>
>>                    <tbody>
>>                        <tr>
>>                            <td><html:text property="usuario" size="20"
>>maxlength="20" /></td>
>>                            <td><html:password property="senha"
>>size="20" maxlength="10"/></td>
>>                        </tr>
>>                        <tr>
>>                            <td>
>>                                <html:submit>
>>                                    <bean:message key="botao.enviar" />
>>                                </html:submit>
>>                            </td>
>>                            <td>
>>                                <html:cancel>
>>                                    <bean:message key="botao.cancelar" />
>>                                </html:cancel>
>>                            </td>
>>                        </tr>
>>                    </tbody>
>>                </html:form>
>>            </table>
>>        </center>
>>        <html:errors />
>>    </body>
>>    <html:javascript formName="LoginUsuarioForm"
>>dynamicJavascript="true" staticJavascript="false"/>
>>
>></html:html>
>>
>>Thanks in advance.
>>Francisco
>>
>>
>>
>>
>>
>>_______________________________________________________
>>Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos
>>emoticons e muito mais. Instale agora!
>>www.yahoo.com.br/messenger/
>>
>>---------------------------------------------------------------------
>>To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
>>For additional commands, e-mail: user-help@struts.apache.org
>>
>>
>>    
>>
>
>
>
>---------------------------------------------------------------------
>To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
>For additional commands, e-mail: user-help@struts.apache.org
>
>
>  
>

	

	
		
_______________________________________________________ 
Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito mais. Instale agora! 
www.yahoo.com.br/messenger/

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


RE: Help - I cannot validate a simple form with 2 fields

Posted by rahul <ra...@amsoft.net>.
try this
 errors.add("usuario", new ActionError("login.usuario.requerido"));


> -----Original Message-----
> From: Francisco Antonio Vieira Souza [mailto:avs1001@yahoo.com.br]
> Sent: Wednesday, September 21, 2005 8:30 PM
> To: Struts Users Mailing List
> Subject: Re: Help - I cannot validate a simple form with 2 fields
>
>
> I really dont get it, I might be being so stupid not figuring out what
> is going on wrong here, but I dont.
>
> Clearing a little. I decided not to use DynaForm and go back to the
> usual ActionForm and gave up using Client-side validation.
>
> When I implement the validate method of the Bean (as it is now) I get
> the error messages as expected, but I had to create a protected method
> to check if the field was null or blank, then put the error message in
> the ActionMessage.
>
> But I dont see any sense in doing such thing like that, why should I do
> this inside validate method if I have already said in validation.xml
> that those fields are REQUIRED, at least that message should be shown to
> the user. Correct me if I am wrong.
>
> If I comment the validate method nothing happen, it is not able to check
> if the field was left blank.
>
> Please be pacience and have a look again:
>
> struts-config.xml:
> <?xml version="1.0" encoding="ISO-8859-1" ?>
>
> <!DOCTYPE struts-config PUBLIC
>           "-//Apache Software Foundation//DTD Struts
> Configuration 1.2//EN"
>           "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
>
>
> <struts-config>
>
>     <form-beans>
>         <!-- This is it -->
>         <form-bean name="LoginUsuarioForm"
> type="br.com.gerente.bean.LoginFormBean"/>
>
>         <form-bean name="GetClienteForm"
> type="br.com.gerente.bean.GetClienteFormBean"/>
>     </form-beans>
>
>     <global-exceptions>
>
>     </global-exceptions>
>
>     <global-forwards>
>         <forward name="welcome"  path="/Clientes.do"/>
>         <forward name="inicio" path="/index.jsp" redirect="true"/>
>     </global-forwards>
>
>     <action-mappings>
>         <!-- This is an action just to call the .jsp file with
> the form -->
>         <action path="/prepararLogin"
>             type="br.com.gerente.action.SuccessAction">
>             <forward name="success" path="/paginas/login.jsp"/>
>         </action>
>
>         <!-- This is my (first) problem in validation -->
>         <action name="LoginUsuarioForm"
>             input="/paginas/login.jsp"
>             path="/LoginUsuario"
>             scope="request"
>             type="br.com.gerente.action.LoginUsuarioAction"
>             validate="true">
>             <forward name="sucesso" path="/paginas/clienteCadastro.jsp"/>
>         </action>
>
>         <!-- This is just the next form to be processed after validating
> the previous -->
>         <action path="/Clientes" forward="/paginas/clienteCadastro.jsp"/>
>
>         <!-- This is another form with the data from the previous
> inputs -->
>         <action name="GetClienteForm"
>             input="/paginas/clienteCadastro.jsp"
>             path="/clientes"
>             scope="request"
>             type="br.com.gerente.action.GetClienteFormAction">
>             <forward name="mostrandoDadosCliente"
>             path="/paginas/clienteDados.jsp"/>
>         </action>
>
>     </action-mappings>
>
>     <controller
> processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
>     <message-resources parameter="br/com/gerente/Resources"/>
>
>     <!-- ========================= Tiles plugin
> ===============================-->
>     <plug-in className="org.apache.struts.tiles.TilesPlugin" >
>         <set-property property="definitions-config"
> value="/WEB-INF/tiles-defs.xml" />
>         <set-property property="moduleAware" value="true" />
>     </plug-in>
>
>     <!-- ========================= Validator plugin
> ================================= -->
>     <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>         <set-property
>         property="pathnames"
>         value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>         <set-property property="stopOnFirstError" value="true" />
>     </plug-in>
>
> </struts-config>
>
> validation.xml:
> <?xml version="1.0" encoding="ISO-8859-1" ?>
>
> <!DOCTYPE form-validation PUBLIC
>           "-//Apache Software Foundation//DTD Commons Validator Rules
> Configuration 1.1.3//EN"
>           "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
>
> <form-validation>
>
>     <global>
>     </global>
>
>     <formset >
>         <constant>
>             <constant-name>postalCode</constant-name>
>             <constant-value>^[0-9a-zA-Z]*$</constant-value>
>         </constant>
>
>         <form name="LoginUsuarioForm">
>             <field property="usuario" depends="required">
>                 <arg key="login.usuario"/>
>             </field>
>             <field property="senha" depends="required">
>                 <arg key="login.senha"/>
>             </field>
>         </form>
>     </formset>
>
> </form-validation>
> //----------------------------------------------------------------
> -----------------------------------------------
>
> /*
>  * LoginFormBean.java
>  *
>  * Created on 21 de Setembro de 2005, 08:25
>  *
> */
>
> package br.com.gerente.bean;
>
> import javax.servlet.http.HttpServletRequest;
> import org.apache.struts.action.ActionMapping;
> import org.apache.struts.action.ActionErrors;
> import org.apache.struts.action.ActionMessage;
>
> public class LoginFormBean extends
> org.apache.struts.validator.ValidatorForm {
>     private String usuario;
>     private String senha;
>     private String senhaConfirmada;
>
>     public LoginFormBean() {
>     }
>
>     public void reset(ActionMapping actionMapping, HttpServletRequest
> request) {
>     }
>
>     public ActionErrors validate(ActionMapping actionMapping,
> HttpServletRequest request) {
>         ActionErrors errors = super.validate( actionMapping, request );
>         if (errors == null) {
>             errors = new ActionErrors(  );
>         }
>         if( nullOrBlank( (String)this.getUsuario()) ) {
>             errors.add("usuario", new
> ActionMessage("login.usuario.requerido"));
>         }
>         if( nullOrBlank( (String)this.getSenha()) ) {
>             errors.add("senha", new
> ActionMessage("login.senha.requerido"));
>         }
>
>         return errors;
>     }
>
>     protected boolean nullOrBlank(String str) {
>         return ((str == null) || (str.length() == 0));
>     }
>
>     public String getUsuario() {
>         return usuario;
>     }
>
>     public void setUsuario(String usuario) {
>         this.usuario = usuario;
>     }
>
>     public String getSenha() {
>         return senha;
>     }
>
>     public void setSenha(String senha) {
>         this.senha = senha;
>     }
>
>     public String getSenhaConfirmada() {
>         return senhaConfirmada;
>     }
>
>     public void setSenhaConfirmada(String senhaConfirmada) {
>         this.senhaConfirmada = senhaConfirmada;
>     }
>
> }
> //----------------------------------------------------------------
> -----------------------------------------------
>
> /*
>  * LoginUsuarioAction.java
>  *
>  * Created on 21 de Setembro de 2005, 09:50
>  *
>  */
>
> package br.com.gerente.action;
>
> import br.com.gerente.bean.GetClienteFormBean;
> import javax.servlet.http.HttpServletRequest;
> import javax.servlet.http.HttpServletResponse;
>
> import org.apache.struts.action.ActionForm;
> import org.apache.struts.action.ActionForward;
> import org.apache.struts.action.ActionMapping;
>
> public class LoginUsuarioAction extends org.apache.struts.action.Action {
>
>     /** Creates a new instance of LoginUsuarioAction */
>     public LoginUsuarioAction() {
>     }
>
>     public ActionForward execute(ActionMapping mapping, ActionForm form,
> HttpServletRequest request, HttpServletResponse response) throws
> Exception {
>         return mapping.findForward("sucesso");
>     }
> }
> //----------------------------------------------------------------
> -----------------------------------------------
>
> Resources.properties:
> #--- erro padrao / default errors --
> errors.header=<font color="red">Erro! Por favor verifique a(s)
> seguinte(s) mensagem(ns):<ul>
> errors.footer=</ul></font>
> errors.prefix=<LI>
> errors.suffix=</LI>
>
> errors.invalid={0} is invalid.
> errors.maxlength={0} can not be greater than {1} characters.
> errors.minlength={0} can not be less than {1} characters.
> errors.range={0} is not in the range {1} through {2}.
> errors.required={0} é obrigatório.
> errors.byte={0} must be an byte.
> errors.date={0} is not a date.
> errors.double={0} must be an double.
> errors.float={0} must be an float.
> errors.integer={0} must be an integer.
> errors.long={0} must be an long.
> errors.short={0} must be an short.
> errors.creditcard={0} is not a valid credit card number.
> errors.email={0} is an invalid e-mail address.
> errors.cancel=Operation cancelled.
> errors.detail={0}
> errors.general=The process did not complete. Details should follow.
> errors.token=Request could not be completed. Operation is not in sequence.
>
> login.titulo=Login de Acesso ao Sistema [G]erente
> login.usuario=Nome de acesso
> login.senha=Senha de acesso
> login.usuario.requerido=Nome de acesso obrigatório
> login.senha.requerido=Senha de acesso obrigatório
>
> # -- botoes/buttons --
> botao.enviar=Enviar Dados
> botao.cancelar=Cancelar
> botao.confirmar=Confirmar
> botao.limpar=Limpar
> botao.salvar=Salvar
> //----------------------------------------------------------------
> -----------------------------------------------
>
> login.jsp:
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
> prefix="bean" %>
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
> prefix="html" %>
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
> prefix="logic" %>
>
> <html:html locale="true">
>     <head>
>         <title><bean:message key="login.titulo"/></title>
>         <html:base/>
>     </head>
>
>     <body>
>         <center>
>             <h1><bean:message key="login.titulo"/></h1>
>
>             <table width="50%">
>                 <html:form action="/LoginUsuario.do" focus="login"
> method="post">
>                     <thead>
>                         <tr>
>                             <th ><bean:message key="login.usuario"/></th>
>                             <th ><bean:message key="login.senha"/></th>
>                         </tr>
>                     </thead>
>                     <tbody>
>                         <tr>
>                             <td><html:text property="usuario" size="20"
> maxlength="20" /></td>
>                             <td><html:password property="senha"
> size="20" maxlength="10"/></td>
>                         </tr>
>                         <tr>
>                             <td>
>                                 <html:submit>
>                                     <bean:message key="botao.enviar" />
>                                 </html:submit>
>                             </td>
>                             <td>
>                                 <html:cancel>
>                                     <bean:message key="botao.cancelar" />
>                                 </html:cancel>
>                             </td>
>                         </tr>
>                     </tbody>
>                 </html:form>
>             </table>
>         </center>
>         <html:errors />
>     </body>
>     <html:javascript formName="LoginUsuarioForm"
> dynamicJavascript="true" staticJavascript="false"/>
>
> </html:html>
>
> Thanks in advance.
> Francisco
>
>
>
>
>
> _______________________________________________________
> Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos
> emoticons e muito mais. Instale agora!
> www.yahoo.com.br/messenger/
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
>
>



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Francisco Antonio Vieira Souza <av...@yahoo.com.br>.
I really dont get it, I might be being so stupid not figuring out what 
is going on wrong here, but I dont.

Clearing a little. I decided not to use DynaForm and go back to the 
usual ActionForm and gave up using Client-side validation.

When I implement the validate method of the Bean (as it is now) I get 
the error messages as expected, but I had to create a protected method 
to check if the field was null or blank, then put the error message in 
the ActionMessage.

But I dont see any sense in doing such thing like that, why should I do 
this inside validate method if I have already said in validation.xml 
that those fields are REQUIRED, at least that message should be shown to 
the user. Correct me if I am wrong.

If I comment the validate method nothing happen, it is not able to check 
if the field was left blank.

Please be pacience and have a look again:

struts-config.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">


<struts-config>
   
    <form-beans>
        <!-- This is it -->
        <form-bean name="LoginUsuarioForm" 
type="br.com.gerente.bean.LoginFormBean"/>
       
        <form-bean name="GetClienteForm" 
type="br.com.gerente.bean.GetClienteFormBean"/>       
    </form-beans>
   
    <global-exceptions>
   
    </global-exceptions>

    <global-forwards>
        <forward name="welcome"  path="/Clientes.do"/>
        <forward name="inicio" path="/index.jsp" redirect="true"/>       
    </global-forwards>

    <action-mappings>
        <!-- This is an action just to call the .jsp file with the form -->
        <action path="/prepararLogin"
            type="br.com.gerente.action.SuccessAction">
            <forward name="success" path="/paginas/login.jsp"/>
        </action>
       
        <!-- This is my (first) problem in validation -->
        <action name="LoginUsuarioForm"
            input="/paginas/login.jsp"
            path="/LoginUsuario"
            scope="request"
            type="br.com.gerente.action.LoginUsuarioAction"
            validate="true">
            <forward name="sucesso" path="/paginas/clienteCadastro.jsp"/>
        </action>
       
        <!-- This is just the next form to be processed after validating 
the previous -->
        <action path="/Clientes" forward="/paginas/clienteCadastro.jsp"/>
       
        <!-- This is another form with the data from the previous inputs -->
        <action name="GetClienteForm"
            input="/paginas/clienteCadastro.jsp"
            path="/clientes"
            scope="request"
            type="br.com.gerente.action.GetClienteFormAction">
            <forward name="mostrandoDadosCliente"
            path="/paginas/clienteDados.jsp"/>
        </action>
               
    </action-mappings>
   
    <controller 
processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
    <message-resources parameter="br/com/gerente/Resources"/>   
   
    <!-- ========================= Tiles plugin 
===============================-->  
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" 
value="/WEB-INF/tiles-defs.xml" />     
        <set-property property="moduleAware" value="true" />
    </plug-in>
   
    <!-- ========================= Validator plugin 
================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
        property="pathnames"
        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
        <set-property property="stopOnFirstError" value="true" />
    </plug-in>
 
</struts-config>

validation.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules 
Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">

<form-validation>

    <global>
    </global>
   
    <formset >
        <constant>
            <constant-name>postalCode</constant-name>
            <constant-value>^[0-9a-zA-Z]*$</constant-value>
        </constant>

        <form name="LoginUsuarioForm">
            <field property="usuario" depends="required">
                <arg key="login.usuario"/>
            </field>
            <field property="senha" depends="required">
                <arg key="login.senha"/>
            </field>           
        </form>       
    </formset>

</form-validation>
//---------------------------------------------------------------------------------------------------------------

/*
 * LoginFormBean.java
 *
 * Created on 21 de Setembro de 2005, 08:25
 *
*/

package br.com.gerente.bean;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

public class LoginFormBean extends 
org.apache.struts.validator.ValidatorForm {
    private String usuario;
    private String senha;
    private String senhaConfirmada;
   
    public LoginFormBean() {
    }
   
    public void reset(ActionMapping actionMapping, HttpServletRequest 
request) {
    }

    public ActionErrors validate(ActionMapping actionMapping, 
HttpServletRequest request) {
        ActionErrors errors = super.validate( actionMapping, request );
        if (errors == null) {
            errors = new ActionErrors(  );
        }
        if( nullOrBlank( (String)this.getUsuario()) ) {
            errors.add("usuario", new 
ActionMessage("login.usuario.requerido"));
        }
        if( nullOrBlank( (String)this.getSenha()) ) {
            errors.add("senha", new ActionMessage("login.senha.requerido"));
        }
       
        return errors;
    }
   
    protected boolean nullOrBlank(String str) {
        return ((str == null) || (str.length() == 0));
    }
   
    public String getUsuario() {
        return usuario;
    }
   
    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }
   
    public String getSenha() {
        return senha;
    }
   
    public void setSenha(String senha) {
        this.senha = senha;
    }
   
    public String getSenhaConfirmada() {
        return senhaConfirmada;
    }
   
    public void setSenhaConfirmada(String senhaConfirmada) {
        this.senhaConfirmada = senhaConfirmada;
    }
   
}
//---------------------------------------------------------------------------------------------------------------

/*
 * LoginUsuarioAction.java
 *
 * Created on 21 de Setembro de 2005, 09:50
 *
 */

package br.com.gerente.action;

import br.com.gerente.bean.GetClienteFormBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LoginUsuarioAction extends org.apache.struts.action.Action {
   
    /** Creates a new instance of LoginUsuarioAction */
    public LoginUsuarioAction() {
    }
   
    public ActionForward execute(ActionMapping mapping, ActionForm form, 
HttpServletRequest request, HttpServletResponse response) throws Exception {
        return mapping.findForward("sucesso");
    }
}
//---------------------------------------------------------------------------------------------------------------

Resources.properties:
#--- erro padrao / default errors --
errors.header=<font color="red">Erro! Por favor verifique a(s) 
seguinte(s) mensagem(ns):<ul>
errors.footer=</ul></font>
errors.prefix=<LI>
errors.suffix=</LI>

errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} é obrigatório.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.

login.titulo=Login de Acesso ao Sistema [G]erente
login.usuario=Nome de acesso
login.senha=Senha de acesso
login.usuario.requerido=Nome de acesso obrigatório
login.senha.requerido=Senha de acesso obrigatório

# -- botoes/buttons --
botao.enviar=Enviar Dados
botao.cancelar=Cancelar
botao.confirmar=Confirmar
botao.limpar=Limpar
botao.salvar=Salvar
//---------------------------------------------------------------------------------------------------------------

login.jsp:
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
prefix="logic" %>

<html:html locale="true">
    <head>
        <title><bean:message key="login.titulo"/></title>
        <html:base/>       
    </head>
   
    <body>
        <center>
            <h1><bean:message key="login.titulo"/></h1>
           
            <table width="50%">
                <html:form action="/LoginUsuario.do" focus="login" 
method="post">
                    <thead>
                        <tr>
                            <th ><bean:message key="login.usuario"/></th>
                            <th ><bean:message key="login.senha"/></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><html:text property="usuario" size="20" 
maxlength="20" /></td>
                            <td><html:password property="senha" 
size="20" maxlength="10"/></td>                       
                        </tr>
                        <tr>
                            <td>
                                <html:submit>
                                    <bean:message key="botao.enviar" />
                                </html:submit>
                            </td>
                            <td>
                                <html:cancel>
                                    <bean:message key="botao.cancelar" />
                                </html:cancel>
                            </td>
                        </tr>
                    </tbody>
                </html:form>
            </table>                       
        </center>
        <html:errors />
    </body>
    <html:javascript formName="LoginUsuarioForm" 
dynamicJavascript="true" staticJavascript="false"/>

</html:html>

Thanks in advance.
Francisco

	

	
		
_______________________________________________________ 
Novo Yahoo! Messenger com voz: ligações, Yahoo! Avatars, novos emoticons e muito mais. Instale agora! 
www.yahoo.com.br/messenger/

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Help - I cannot validate a simple form with 2 fields

Posted by Niall Pemberton <ni...@blueyonder.co.uk>.
On the client side validation it looks like you have spelt the javascript
method name wrong in the form's onsubmit event. You can easily check the
client side by seeing what javascript has been generated for the page by
viewing the source.

For the sever side I can't see anything obviously wrong. Probably the best
approach would be to switch on "debug" level logging for the
RequestProcessor - it will tell you whats happening when it does the
processValidate() method.

The one thing I'm wondering is - do you have a "default" formset (i.e. one
with no language/country specified) in your validation.xml? In case it is
not using the pt_BR locale for some reason it would be a good idea to have a
default formset.

Niall

----- Original Message ----- 
From: "Francisco Antonio Vieira Souza" <av...@yahoo.com.br>
To: <us...@struts.apache.org>
Sent: Tuesday, September 20, 2005 7:48 PM
Subject: Help - I cannot validate a simple form with 2 fields


> Hi all,
>
> I really need a big help in validation with Struts, I dont know why but
> I just cant validate a very simple form I have, with 2 simple fields
> (login and password), I have follown all tutorials I got but til now no
> success.
>
> I am not able to validate either in server side or client side.
>
> I am using Struts 1.2.7 - Is there any big difference in validating with
> this version and the previous ones?
>
> Here are the stpeds I did:
>
> 1) created the DynaValidatorForm in struts-config and mapped the Actions
> it there too.
>
//--------------------------------------------------------------------------
-----------
> ....
> <form-beans>
>        <form-bean name="loginForm"
> type="org.apache.struts.validator.DynaValidatorForm">
>            <form-property name="login" type="java.lang.String" />
>            <form-property name="senha" type="java.lang.String" />
>            <form-property name="senha2" type="java.lang.String" />
>        </form-bean>
>    </form-beans>
> ....
> <!-- this one is called to show the page with the fields -->
> <action path="/prepararLogin"
>            type="br.com.gerente.SuccessAction">
>            <forward name="success" path="/paginas/login.jsp"/>
> </action>
>
> <!-- this one is processed when the submit button is pressed -->
> <action path="/Login"
>            type="br.com.gerente.ProcessaLoginDynaAction"
>            name="loginForm"
>            scope="request"
>            input="input"
>            validate="true">
>            <forward name="success" path="/paginas/clienteCadastro.jsp"/>
>            <forward name="input" path="/prepararLogin.do" />
> </action>
> ...
> <message-resources parameter="br/com/gerente/Resources"/>   ...
>    <!-- ========================= Validator plugin
> ================================= -->
>    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
>        <set-property
>        property="pathnames"
>        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
>        <set-property property="stopOnFirstError" value="true" />
>    </plug-in>
>
> 2) create the action to call the login.jsp (and others):
SuccessAction.java
>
//--------------------------------------------------------------------------
-----------
> package br.com.gerente;
>
> import javax.servlet.http.HttpServletRequest;
> import javax.servlet.http.HttpServletResponse;
>
> import org.apache.struts.action.Action;
> import org.apache.struts.action.ActionForm;
> import org.apache.struts.action.ActionForward;
> import org.apache.struts.action.ActionMapping;
>
> public class SuccessAction extends Action {
>      /** Creates a new instance of SuccessAction */
>    public SuccessAction() {
>        super();
>    }
>      /**
>     * Returns the <code>ActionForward</code> named "success" if one is
>     * configured or <code>null</code>if it cannot be found.
>     *
>     * Searches first for a local forward, then a global forward.
>     *
>     * @param mapping The ActionMapping used to select this instance
>     * @param form The optional ActionForm bean for this request (if any)
>     * @param request The HTTP request we are processing
>     * @param response The HTTP response we are creating
>     *
>     * @exception Exception if mapping.findForward throws an Exception
>     *
>     * @return the "success" ActionForward, or null if it cannot be found
>     */
>    public ActionForward execute(
>            ActionMapping mapping,
>            ActionForm form,
>            HttpServletRequest request,
>            HttpServletResponse response)
>            throws Exception {
>              return mapping.findForward("success");
>          }
> }
>
> 3) created the action: ProcessaLoginDynaAction.java
> package br.com.gerente;
>
> import javax.servlet.http.HttpServletRequest;
> import javax.servlet.http.HttpServletResponse;
>
> import org.apache.struts.action.Action;
> import org.apache.struts.action.ActionForm;
> import org.apache.struts.action.ActionForward;
> import org.apache.struts.action.ActionMapping;
> import org.apache.struts.validator.DynaValidatorForm;
>
> public class ProcessaLoginDynaAction extends Action {
>      /** Creates a new instance of ProcessaLoginDynaAction */
>    public ProcessaLoginDynaAction() {
>        super();
>    }
>      /**
>     * Process the request and return an <code>ActionForward</code>
instance
>     * describing where and how control should be forwarded, or
>     * <code>null</code>if the response has already been completed.
>     *
>     * @param mapping The ActionMapping used to select this instance
>     * @param form The optional ActionForm bean for this request (if any)
>     * @param request The HTTP request we are processing
>     * @param response The HTTP response we are creating
>     *
>     * @exception Exception if the application logic throws an exception
>     *
>     * @return the ActionForward for the next view
>     */
>    public ActionForward execute(
>            ActionMapping mapping,
>            ActionForm form,
>            HttpServletRequest request,
>            HttpServletResponse response)
>            throws Exception {
>              // Se o usuario pressionar o botao 'Cancelar' volta para o
> inicio
>        if (isCancelled(request)) {
>            return mapping.findForward("inicio");
>        }
>        DynaValidatorForm dynaForm = (DynaValidatorForm)form;
>        //dynaForm.set("login","nome do login");
>        //System.out.println("Login: "+dynaForm.get("login") );
>        // Forward to result page
>        return mapping.findForward("success");
>    } }
>
> 4) created login.jsp:
>
//--------------------------------------------------------------------------
-----------
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
> prefix="bean" %>
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
> prefix="html" %>
> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
> prefix="logic" %>
>
> <html:html locale="true">
>    <head>
>        <title><bean:message key="login.titulo"/></title>
>        <html:base/>
>        <link rel="stylesheet" type="text/css" href="estilo.css" />
>    </head>
>    <body>
>        <center>
>            <h1><bean:message key="login.titulo"/></h1>
>                      <html:errors property="login"/>
>                          <table border="0" width="50%">
>                <html:form action="/Login.do" focus="login" method="post"
> onsubmit="return validateformLogin(this)">
>                    <thead>
>                        <tr>
>                            <th></th>
>                            <th></th>
>                        </tr>
>                    </thead>
>                    <tbody>
>                        <tr>
>                            <td class="into"><bean:message
> key="login.nome"/></td>
>                            <td>
>                                <html:text property="login" size="20"
> maxlength="20" />
>                            </td>
>                        </tr>
>                        <tr>
>                            <td><bean:message key="login.senha"/></td>
>                            <td><html:password property="senha" size="20"
> maxlength="10"/></td>
>                        </tr>
>                        <tr>
>                            <td></td>
>                            <td>
>                                <html:submit>
>                                    <bean:message key="botao.enviar" />
>                                </html:submit>
>                                <html:cancel>
>                                    <bean:message key="botao.cancelar" />
>                                </html:cancel>
>                            </td>
>                        </tr>
>                    </tbody>
>                </html:form>
>            </table>                              </center>
</body>
>    <html:javascript formName="loginForm" dynamicJavascript="true"
> staticJavascript="false"/>
> </html:html>
>
> 5) The resources file: Resources.properties
>
//--------------------------------------------------------------------------
-----------
> #--- erro padrao --
> errors.header=<font color="red">Erro! Por favor verifique a(s)
> seguinte(s) mensagem(ns):<ul>
> errors.footer=</ul></font>
> errors.prefix=<LI>
> errors.suffix=</LI>
>
> errors.invalid={0} is invalid.
> errors.maxlength={0} can not be greater than {1} characters.
> errors.minlength={0} can not be less than {1} characters.
> errors.range={0} is not in the range {1} through {2}.
> errors.required={0} é obrigatório.
> errors.byte={0} must be an byte.
> errors.date={0} is not a date.
> errors.double={0} must be an double.
> errors.float={0} must be an float.
> errors.integer={0} must be an integer.
> errors.long={0} must be an long.
> errors.short={0} must be an short.
> errors.creditcard={0} is not a valid credit card number.
> errors.email={0} is an invalid e-mail address.
> errors.cancel=Operation cancelled.
> errors.detail={0}
> errors.general=The process did not complete. Details should follow.
> errors.token=Request could not be completed. Operation is not in sequence.
> welcome.title=Struts Application
> sistema.titulo=Sistema de Gerenciamento dos Clientes da Kooky
> cliente.titulo.cadastro=Cadastro de Clientes
> cliente.titulo.dados=Cadastro de Clientes - Dados
> welcome.heading=Struts Applications in Netbeans!
> welcome.message=It's easy to create Struts applications with NetBeans.
>
> login.titulo=Login de Acesso ao Sistema [G]erente
> login.nome=Nome de acesso
> login.senha=Senha de acesso
>
> erro.data=Data Invalida
> erro.obrigatorio=Dados obrigatorio
> erro.email=Email errado
>
> # -- campos obrigatorios --
> id.obrigatorio=O Indentificador é obrigatório
>
> # -- formatando --
> formato.data=dd/MM/yyyy
> formato.moeda=R$ #.##0,00;R$ (#.##0,00)
>
> # -- botoes --
> botao.enviar=Enviar Dados
> botao.cancelar=Cancelar
> botao.confirmar=Confirmar
> botao.limpar=Limpar
> botao.salvar=Salvar
>
> 6) the validation.xml:
>
//--------------------------------------------------------------------------
-----------
> <formset language="pt" country="BR" >
>
>        <constant>
>            <constant-name>postalCode</constant-name>
>            <constant-value>^[0-9a-zA-Z]*$</constant-value>
>        </constant>
>
>        <form name="loginForm">
>            <field property="login" depends="required">
>                <arg key="login.nome"/>
>            </field>
>            <field property="senha" depends="required">
>                <arg key="login.senha"/>
>            </field>
>        </form>
> </formset>
>
>
//--------------------------------------------------------------------------
-----------
> So, according to the mapping action when I press the submit button with
> the fileds empty it should show me 2 messages in the page, right? But it
> does not show anything, just call the next page.
> What am I doing wrong?
> I really would appreciate any help from you guys.
>
> Thanks in advance.
> Francisco.



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org