You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by Andrej Sobkowski <as...@hotmail.com> on 2001/11/02 16:15:25 UTC

Validator design considerations

Hello All,

I have a set of design considerations/suggestions for the Validation 
Framework in Struts. Let me know if I'm totally missing the point.

I like the whole Validator approach, in particular the XML configuration. I 
believe that's the way to go, but I'd like to discuss a few points.

DISCUSSION: The Validator is quite "linked" to Servlet's stuff 
(HttpServletRequest) and to FormBean. If I got it right, currently the 
Validator needs a set of parameters to be passed to the ValidatorAction, 
including the bean to validate, the Field and some Servlet parameters.

In a similar way, the validation process is linked to the FormBean 
(validate() in FormBean class).

Shouldn't they be separate?
- The Action should take care of the HTTP stuff while the Validator should 
only have knowledge of the bean and the corresponding fields to be 
validated.
- The form bean itself is a "special data holder" and shouldn't be aware of 
how its data is validated. Do you agree?

I was thinking at something like the following (pseudo-code):

* CONFIGURATION file (new DTD for struts-config.xml or separate file)
  <action    path="/login"
             type="com.mycompany.myActionWithValidation"
             name="myForm">
    <!-- add validation on myForm's property 'lastName' that will check via 
a SizeValidator
         that the size of the field is between 1 and 15 chars. If not, the 
message will be
         returned in the ValidationException (I18N can be added easily) -->
    <validation property="lastName"
                validator="com.mycompany.SizeValidator"
                arg0="1"
                arg1="15"
                message="Last Name is mandatory and can't be longer than 15 
chars" />
    ...
  </action>

* JAVA CODE
public interface IValidator(Object bean) {
  +validate() throws ValidationException;
}

public class Action {
  ...
  +addValidator(IValidator val)
  +validators(): Iterator // returns an Iterator on all validators for the 
action
}

// Validator that checks if text size is >min and < max (for example).
// It can be easily extended to check int min/max and so on.
public class SizeValidator {
  ... // min/max

  public void validate(Object bean) throws ValidationException {
    Object value = getPropertyValue(bean);
    if (value instanceof String) {
      // Check String size
      String check = (String)value;
      if ((check.length() > maxSize) ||
          (check.length() < minSize)) {
          // Validation failed: throw exception
          // with corresponding error message (defined in conf)
          throwException(getValidationMessage());
      }
    } else {
      // Error, wrong class type...
    }
  }
}


// Minor changes to ActionServlet
public class ActionServlet {
  ...
  public void processInitValidatorsForAction(..) {
  // By reading the XML configuration file, the ActionServlet will execute a 
set of addValidator(..)
  // For example, consider the following XML struts-config.xml (DTD to be 
modified)
  // <action
  curAction.addValidator(new SizeValidator("lastName", "1", "15");
  curAction.addValidator(new RegExpValidator("phone", "(999)999-9999");
  ...
  }

  // Executes all validators on FormBean(s) for action executed
  public ActionErrors processValidate(...) {
    Iterator it = action.validators();
    try {
      ((Validator)it.next()).validate(formBean); // the validator validates 
the form bean only
    } catch (ValidationException e) {
      Log.debug("Validation failed!", e);
      errors.addError(e.getMessage()); // Add multilanguage
    }
  }
}

Useless to say, this is only a high-level point of view. It does work on my 
prototype (no XML config), but it can be enhanced and optimized in many 
ways. I think it's also conceptually pretty close to what is currently done 
in the Validator.

The Validators can be designed as desired. To compare two values, simply 
define a validator like CompareValidator(property1, property2, compareRule) 
with compareRule = "<", ">",...

What do you think?

Thanks.

Andrej

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp


--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by Adam <ad...@getcare.com>.
I actually built out a very similar framework back in my ATG days. 
 Greate minds stink alike....

Not so sure how much logic you want to put into the XML.  I would rather 
have Form validators that have access to a slew of page validation rules.

One possiblity is

MyFormValidator extends FormValidator(){
 
 public void validate(ActionForm form){
    MyForm myForm = (MyForm)form;
 
     validateNotBlank(myForm.getName(), BLANK_MESSAGE);
     validateWithinRange(MIN_VAL, MAX_VAL, myForm.getIntVal(), 
OUT_OF_RANGE_MESSAGE);
   }
}

Obviously this is very similar to what you would have written in the XML 
but with three advantages:
1.  You can do much more complex logic in the Java code
2.  You can run a test like this in an offline (not running 
ServletEngine) environment to check your business logic.
3.  You don't end up with all your coders vying for control of the 
struts-config.xml file with the corresponding merge problems.

However, I don't think anything you have specified precludes doing work 
in the Java level, just that it is possible in the struts-config.xml level.

Validators would all be application scope beans and designed to be 
Stateless.  You can have one validator call another, and so on.  

I guess that this does not preclude you from doing simple Validation in 
the XML.  And yes, you could do it in a onther file as you suggested 
below.  But I prefer to thin of the XML files as a registry:  They are 
the way one thing finds another.  Keep your serious logic in the Java code.

And please do not name interfaces with Hungarian Notation (IValidator) 
 Aside from violating the Java coding standards, it give me flashbacks 
to my Microsoft Visuall C++ days.  Shudder.
  May I suggest in its place the more friendly Validatable?  Actually, 
you probably will find that this should be an abstract class that you 
have to fill in the blanks on.  The one I wrote before returned an 
Exception that was just a collection of the FormValidation errors, with 
messages attached for display purposes.  Then you provide method to dump 
the results of an internal Validation into the scope of the current 
validation.


Another suggestion.  For the inistialization of the Validators,  use XML 
like

  <validatator
               name="lastNameValidator"
               property="lastName"
               validator="com.mycompany.SizeValidator"
               message="Last Name is mandatory and can't be longer than 
15 chars" >
      <param name="minimum" type="java.lang.Integer"  value="3" />
      <param name="maximum" type="java.lang.Integer"  value="15" />
</validation>

Where each of the parameters are set according to the rules of java bean 
properties.


and then in the action
<validation name="lastNameValidator" />


Actually, this would be nice to have for form initialization as 
well....hmmmmm.


Andrej Sobkowski wrote:

> Hello All,
>
> I have a set of design considerations/suggestions for the Validation 
> Framework in Struts. Let me know if I'm totally missing the point.
>
> I like the whole Validator approach, in particular the XML 
> configuration. I believe that's the way to go, but I'd like to discuss 
> a few points.
>
> DISCUSSION: The Validator is quite "linked" to Servlet's stuff 
> (HttpServletRequest) and to FormBean. If I got it right, currently the 
> Validator needs a set of parameters to be passed to the 
> ValidatorAction, including the bean to validate, the Field and some 
> Servlet parameters.
>
> In a similar way, the validation process is linked to the FormBean 
> (validate() in FormBean class).
>
> Shouldn't they be separate?
> - The Action should take care of the HTTP stuff while the Validator 
> should only have knowledge of the bean and the corresponding fields to 
> be validated.
> - The form bean itself is a "special data holder" and shouldn't be 
> aware of how its data is validated. Do you agree?
>
> I was thinking at something like the following (pseudo-code):
>
> * CONFIGURATION file (new DTD for struts-config.xml or separate file)
>  <action    path="/login"
>             type="com.mycompany.myActionWithValidation"
>             name="myForm">
>    <!-- add validation on myForm's property 'lastName' that will check 
> via a SizeValidator
>         that the size of the field is between 1 and 15 chars. If not, 
> the message will be
>         returned in the ValidationException (I18N can be added easily) 
> -->
>    <validation property="lastName"
>                validator="com.mycompany.SizeValidator"
>                arg0="1"
>                arg1="15"
>                message="Last Name is mandatory and can't be longer 
> than 15 chars" />
>    ...
>  </action>
>
> * JAVA CODE
> public interface IValidator(Object bean) {
>  +validate() throws ValidationException;
> }
>
> public class Action {
>  ...
>  +addValidator(IValidator val)
>  +validators(): Iterator // returns an Iterator on all validators for 
> the action
> }
>
> // Validator that checks if text size is >min and < max (for example).
> // It can be easily extended to check int min/max and so on.
> public class SizeValidator {
>  ... // min/max
>
>  public void validate(Object bean) throws ValidationException {
>    Object value = getPropertyValue(bean);
>    if (value instanceof String) {
>      // Check String size
>      String check = (String)value;
>      if ((check.length() > maxSize) ||
>          (check.length() < minSize)) {
>          // Validation failed: throw exception
>          // with corresponding error message (defined in conf)
>          throwException(getValidationMessage());
>      }
>    } else {
>      // Error, wrong class type...
>    }
>  }
> }
>
>
> // Minor changes to ActionServlet
> public class ActionServlet {
>  ...
>  public void processInitValidatorsForAction(..) {
>  // By reading the XML configuration file, the ActionServlet will 
> execute a set of addValidator(..)
>  // For example, consider the following XML struts-config.xml (DTD to 
> be modified)
>  // <action
>  curAction.addValidator(new SizeValidator("lastName", "1", "15");
>  curAction.addValidator(new RegExpValidator("phone", "(999)999-9999");
>  ...
>  }
>
>  // Executes all validators on FormBean(s) for action executed
>  public ActionErrors processValidate(...) {
>    Iterator it = action.validators();
>    try {
>      ((Validator)it.next()).validate(formBean); // the validator 
> validates the form bean only
>    } catch (ValidationException e) {
>      Log.debug("Validation failed!", e);
>      errors.addError(e.getMessage()); // Add multilanguage
>    }
>  }
> }
>
> Useless to say, this is only a high-level point of view. It does work 
> on my prototype (no XML config), but it can be enhanced and optimized 
> in many ways. I think it's also conceptually pretty close to what is 
> currently done in the Validator.
>
> The Validators can be designed as desired. To compare two values, 
> simply define a validator like CompareValidator(property1, property2, 
> compareRule) with compareRule = "<", ">",...
>
> What do you think?
>
> Thanks.
>
> Andrej
>
> _________________________________________________________________
> Get your FREE download of MSN Explorer at 
> http://explorer.msn.com/intl.asp
>
>
> -- 
> To unsubscribe, e-mail:   
> <ma...@jakarta.apache.org>
> For additional commands, e-mail: 
> <ma...@jakarta.apache.org>
>
>
>



--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by Ted Husted <hu...@apache.org>.
Andrej Sobkowski wrote:
> - The form bean itself is a "special data holder" and shouldn't be aware of
> how its data is validated. Do you agree?

I'm not sure that I do. I like to think of the ActionForm as a firewall.
If it has passes the intial validation, then I know it is "safe" to use,
and can passed along to business methods. Generally, objects should have
dominion over their own data.

Under the current model, the bean is not even passed to the Action until
it is validated. The Action may undertake additional validation, usually
in collaboration with the business model, but I think it is valid for an
ActionForm to know whether it's String values pass some form of "prima
facia" validation.

There is usually additional validation at the business logic level, but
this is different from the type of validation we need on ActionForms --
like did they even enter anything? Could it even be a number?

I do believe we should be able to incorporate the XML configuration in
to the Struts config, so that it is near the ActionForm bean it
validates, but I'm not sure if "primary" validation should be delegated
to another object, if that's what you're suggesting. 

We could definately use more standard, backend validators, but,
personally, I would say that the framework object that calls the
standard validator with the property in question should be the
ActionForm, or a business object, and not the Action or ActionServlet
directly.

-- Ted Husted, Husted dot Com, Fairport NY USA.
-- Custom Software ~ Technical Services.
-- Tel +1 716 737-3463
-- http://www.husted.com/struts/


Andrej Sobkowski wrote:
> 
> Hello All,
> 
> I have a set of design considerations/suggestions for the Validation
> Framework in Struts. Let me know if I'm totally missing the point.
> 
> I like the whole Validator approach, in particular the XML configuration. I
> believe that's the way to go, but I'd like to discuss a few points.
> 
> DISCUSSION: The Validator is quite "linked" to Servlet's stuff
> (HttpServletRequest) and to FormBean. If I got it right, currently the
> Validator needs a set of parameters to be passed to the ValidatorAction,
> including the bean to validate, the Field and some Servlet parameters.
> 
> In a similar way, the validation process is linked to the FormBean
> (validate() in FormBean class).
> 
> Shouldn't they be separate?
> - The Action should take care of the HTTP stuff while the Validator should
> only have knowledge of the bean and the corresponding fields to be
> validated.
> - The form bean itself is a "special data holder" and shouldn't be aware of
> how its data is validated. Do you agree?
> 
> I was thinking at something like the following (pseudo-code):
> 
> * CONFIGURATION file (new DTD for struts-config.xml or separate file)
>   <action    path="/login"
>              type="com.mycompany.myActionWithValidation"
>              name="myForm">
>     <!-- add validation on myForm's property 'lastName' that will check via
> a SizeValidator
>          that the size of the field is between 1 and 15 chars. If not, the
> message will be
>          returned in the ValidationException (I18N can be added easily) -->
>     <validation property="lastName"
>                 validator="com.mycompany.SizeValidator"
>                 arg0="1"
>                 arg1="15"
>                 message="Last Name is mandatory and can't be longer than 15
> chars" />
>     ...
>   </action>
> 
> * JAVA CODE
> public interface IValidator(Object bean) {
>   +validate() throws ValidationException;
> }
> 
> public class Action {
>   ...
>   +addValidator(IValidator val)
>   +validators(): Iterator // returns an Iterator on all validators for the
> action
> }
> 
> // Validator that checks if text size is >min and < max (for example).
> // It can be easily extended to check int min/max and so on.
> public class SizeValidator {
>   ... // min/max
> 
>   public void validate(Object bean) throws ValidationException {
>     Object value = getPropertyValue(bean);
>     if (value instanceof String) {
>       // Check String size
>       String check = (String)value;
>       if ((check.length() > maxSize) ||
>           (check.length() < minSize)) {
>           // Validation failed: throw exception
>           // with corresponding error message (defined in conf)
>           throwException(getValidationMessage());
>       }
>     } else {
>       // Error, wrong class type...
>     }
>   }
> }
> 
> // Minor changes to ActionServlet
> public class ActionServlet {
>   ...
>   public void processInitValidatorsForAction(..) {
>   // By reading the XML configuration file, the ActionServlet will execute a
> set of addValidator(..)
>   // For example, consider the following XML struts-config.xml (DTD to be
> modified)
>   // <action
>   curAction.addValidator(new SizeValidator("lastName", "1", "15");
>   curAction.addValidator(new RegExpValidator("phone", "(999)999-9999");
>   ...
>   }
> 
>   // Executes all validators on FormBean(s) for action executed
>   public ActionErrors processValidate(...) {
>     Iterator it = action.validators();
>     try {
>       ((Validator)it.next()).validate(formBean); // the validator validates
> the form bean only
>     } catch (ValidationException e) {
>       Log.debug("Validation failed!", e);
>       errors.addError(e.getMessage()); // Add multilanguage
>     }
>   }
> }
> 
> Useless to say, this is only a high-level point of view. It does work on my
> prototype (no XML config), but it can be enhanced and optimized in many
> ways. I think it's also conceptually pretty close to what is currently done
> in the Validator.
> 
> The Validators can be designed as desired. To compare two values, simply
> define a validator like CompareValidator(property1, property2, compareRule)
> with compareRule = "<", ">",...
> 
> What do you think?
> 
> Thanks.
> 
> Andrej
> 
> _________________________________________________________________
> Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp
> 
> --
> To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
> For additional commands, e-mail: <ma...@jakarta.apache.org>


> 
> Hello All,
> 
> I have a set of design considerations/suggestions for the Validation
> Framework in Struts. Let me know if I'm totally missing the point.
> 
> I like the whole Validator approach, in particular the XML configuration. I
> believe that's the way to go, but I'd like to discuss a few points.
> 
> DISCUSSION: The Validator is quite "linked" to Servlet's stuff
> (HttpServletRequest) and to FormBean. If I got it right, currently the
> Validator needs a set of parameters to be passed to the ValidatorAction,
> including the bean to validate, the Field and some Servlet parameters.
> 
> In a similar way, the validation process is linked to the FormBean
> (validate() in FormBean class).
> 
> Shouldn't they be separate?
> - The Action should take care of the HTTP stuff while the Validator should
> only have knowledge of the bean and the corresponding fields to be
> validated.
> - The form bean itself is a "special data holder" and shouldn't be aware of
> how its data is validated. Do you agree?
> 
> I was thinking at something like the following (pseudo-code):
> 
> * CONFIGURATION file (new DTD for struts-config.xml or separate file)
>   <action    path="/login"
>              type="com.mycompany.myActionWithValidation"
>              name="myForm">
>     <!-- add validation on myForm's property 'lastName' that will check via
> a SizeValidator
>          that the size of the field is between 1 and 15 chars. If not, the
> message will be
>          returned in the ValidationException (I18N can be added easily) -->
>     <validation property="lastName"
>                 validator="com.mycompany.SizeValidator"
>                 arg0="1"
>                 arg1="15"
>                 message="Last Name is mandatory and can't be longer than 15
> chars" />
>     ...
>   </action>
> 
> * JAVA CODE
> public interface IValidator(Object bean) {
>   +validate() throws ValidationException;
> }
> 
> public class Action {
>   ...
>   +addValidator(IValidator val)
>   +validators(): Iterator // returns an Iterator on all validators for the
> action
> }
> 
> // Validator that checks if text size is >min and < max (for example).
> // It can be easily extended to check int min/max and so on.
> public class SizeValidator {
>   ... // min/max
> 
>   public void validate(Object bean) throws ValidationException {
>     Object value = getPropertyValue(bean);
>     if (value instanceof String) {
>       // Check String size
>       String check = (String)value;
>       if ((check.length() > maxSize) ||
>           (check.length() < minSize)) {
>           // Validation failed: throw exception
>           // with corresponding error message (defined in conf)
>           throwException(getValidationMessage());
>       }
>     } else {
>       // Error, wrong class type...
>     }
>   }
> }
> 
> // Minor changes to ActionServlet
> public class ActionServlet {
>   ...
>   public void processInitValidatorsForAction(..) {
>   // By reading the XML configuration file, the ActionServlet will execute a
> set of addValidator(..)
>   // For example, consider the following XML struts-config.xml (DTD to be
> modified)
>   // <action
>   curAction.addValidator(new SizeValidator("lastName", "1", "15");
>   curAction.addValidator(new RegExpValidator("phone", "(999)999-9999");
>   ...
>   }
> 
>   // Executes all validators on FormBean(s) for action executed
>   public ActionErrors processValidate(...) {
>     Iterator it = action.validators();
>     try {
>       ((Validator)it.next()).validate(formBean); // the validator validates
> the form bean only
>     } catch (ValidationException e) {
>       Log.debug("Validation failed!", e);
>       errors.addError(e.getMessage()); // Add multilanguage
>     }
>   }
> }
> 
> Useless to say, this is only a high-level point of view. It does work on my
> prototype (no XML config), but it can be enhanced and optimized in many
> ways. I think it's also conceptually pretty close to what is currently done
> in the Validator.
> 
> The Validators can be designed as desired. To compare two values, simply
> define a validator like CompareValidator(property1, property2, compareRule)
> with compareRule = "<", ">",...
> 
> What do you think?
> 
> Thanks.
> 
> Andrej
> 
> _________________________________________________________________
> Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp
> 
> --
> To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
> For additional commands, e-mail: <ma...@jakarta.apache.org>

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by David Winterfeldt <dw...@yahoo.com>.
I don't mind the idea of combining or changing the XML
configuration for validations.  I think that the
validation rules are getting very long at the top of
the Validator and need to be moved to a separate file
(at least for the default ones).

I have some comments interspersed below on some other
issues.

David

--- Andrej Sobkowski <as...@hotmail.com> wrote:
> Hello All,
> 
> I have a set of design considerations/suggestions
> for the Validation 
> Framework in Struts. Let me know if I'm totally
> missing the point.
> 
> I like the whole Validator approach, in particular
> the XML configuration. I 
> believe that's the way to go, but I'd like to
> discuss a few points.
> 
> DISCUSSION: The Validator is quite "linked" to
> Servlet's stuff 
> (HttpServletRequest) and to FormBean. If I got it
> right, currently the 
> Validator needs a set of parameters to be passed to
> the ValidatorAction, 
> including the bean to validate, the Field and some
> Servlet parameters.
I don't see how the validator is "linked" to the
servlet.  The default method signature for Struts is
tied to Servlet specific things, but none of the
default validation use it.  The default method
signature gives you a full handle on the environment
so you can do whatever you need to do for a
validation.  Retrieve another object from scope to
compare to this one, retrieve database information,
etc.  If you want to not have this information passed
to validation methods, you can create your own
validators and override the default signature by using
the methodParams attribute.

methodParams="java.lang.Object,com.wintecinc.struts.validation.Field,java.util.List"

Look at the section on validating outside of Struts.
http://home.earthlink.net/~dwinterfeldt/overview.html#validatingOutsideOfStruts


> 
> In a similar way, the validation process is linked
> to the FormBean 
> (validate() in FormBean class).
> 
> Shouldn't they be separate?
> - The Action should take care of the HTTP stuff
> while the Validator should 
> only have knowledge of the bean and the
> corresponding fields to be 
> validated.
> - The form bean itself is a "special data holder"
> and shouldn't be aware of 
> how its data is validated. Do you agree?
Well the ActionForm isn't really aware of how it is
validated when you use the validation framework.  It
just has a validate method that calls something else
that is aware how it should be validated.

> 
> I was thinking at something like the following
> (pseudo-code):
> 
> * CONFIGURATION file (new DTD for struts-config.xml
> or separate file)
>   <action    path="/login"
>             
> type="com.mycompany.myActionWithValidation"
>              name="myForm">
>     <!-- add validation on myForm's property
> 'lastName' that will check via 
> a SizeValidator
>          that the size of the field is between 1 and
> 15 chars. If not, the 
> message will be
>          returned in the ValidationException (I18N
> can be added easily) -->
>     <validation property="lastName"
>                
> validator="com.mycompany.SizeValidator"
>                 arg0="1"
>                 arg1="15"
>                 message="Last Name is mandatory and
> can't be longer than 15 
> chars" />
>     ...
>   </action>
I think it is good to have the validator defined
elsewhere so there can be defaults and if you want
matching Javascript for this it would make the action
very hard to read by placing the validator reference
here.  That doesn't mean that arguments could be
passed in here though.

> 
> * JAVA CODE
> public interface IValidator(Object bean) {
>   +validate() throws ValidationException;
> }
> 
> public class Action {
>   ...
>   +addValidator(IValidator val)
>   +validators(): Iterator // returns an Iterator on
> all validators for the 
> action
> }
> 
> // Validator that checks if text size is >min and <
> max (for example).
> // It can be easily extended to check int min/max
> and so on.
> public class SizeValidator {
>   ... // min/max
> 
>   public void validate(Object bean) throws
> ValidationException {
>     Object value = getPropertyValue(bean);
>     if (value instanceof String) {
>       // Check String size
>       String check = (String)value;
>       if ((check.length() > maxSize) ||
>           (check.length() < minSize)) {
>           // Validation failed: throw exception
>           // with corresponding error message
> (defined in conf)
>           throwException(getValidationMessage());
>       }
>     } else {
>       // Error, wrong class type...
>     }
>   }
> }
> 
> 
> // Minor changes to ActionServlet
> public class ActionServlet {
>   ...
>   public void processInitValidatorsForAction(..) {
>   // By reading the XML configuration file, the
> ActionServlet will execute a 
> set of addValidator(..)
>   // For example, consider the following XML
> struts-config.xml (DTD to be 
> modified)
>   // <action
>   curAction.addValidator(new
> SizeValidator("lastName", "1", "15");
>   curAction.addValidator(new
> RegExpValidator("phone", "(999)999-9999");
>   ...
>   }
> 
>   // Executes all validators on FormBean(s) for
> action executed
>   public ActionErrors processValidate(...) {
>     Iterator it = action.validators();
>     try {
>       ((Validator)it.next()).validate(formBean); //
> the validator validates 
> the form bean only
>     } catch (ValidationException e) {
>       Log.debug("Validation failed!", e);
>       errors.addError(e.getMessage()); // Add
> multilanguage
>     }
>   }
> }
> 
> Useless to say, this is only a high-level point of
> view. It does work on my 
> prototype (no XML config), but it can be enhanced
> and optimized in many 
> ways. I think it's also conceptually pretty close to
> what is currently done 
> in the Validator.
> 
> The Validators can be designed as desired. To
> compare two values, simply 
> define a validator like CompareValidator(property1,
> property2, compareRule) 
> with compareRule = "<", ">",...
> 
> What do you think?
> 
> Thanks.
> 
> Andrej
> 
>
_________________________________________________________________
> Get your FREE download of MSN Explorer at
> http://explorer.msn.com/intl.asp
> 


__________________________________________________
Do You Yahoo!?
Find a job, post your resume.
http://careers.yahoo.com

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by "emmanuel.boudrant" <b7...@yahoo.fr>.
I'm working ont it,

For validation, I suggest an external XML file based
on regular expression, in this case we are able to
generate and synchronise validator functions on client
and server size.

ex:

******************************************
*Server size: (with project jakarta regexp)

    public ActionErrors validate (ActionMapping
mapping, HttpServletRequest request) {
        ActionErrors errors=null;
        // Get the action errors by checking this
instance and rules describe in
        // form-rules.xml
        try {
            errors = ReValidator.actionErrors(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Check others errors. Errors cannot be
explain in form-rules.xml
        // Return errors.
        return  errors;
    }

************************************************
*Client side:

<!-- Javascript validate function for check.do -->
<script language="javascript">
function testField(field, regexp) {
 if ( field != null && field.value != "" &&
field.value != null) {
   var myRe = regexp.exec(field.value);
   if ( !myRe ) {
     return false;
   } else { 
     return true;
   }
 }
 return true;
}

function validate() {
	var text="";
 if ( document.myForm.email.value == "" ||
document.myForm.email.value == null ) text +=
("email:*.\n");
 else  if (
!testField(document.myForm.email,/[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+/)
)
    text += ("email:[email invalide].\n")
(...)
 if ( text == "" ) return true;
 alert("Erreur de saisie:\n\n" + text);
 return false;
}
</script>

****************************************************
*And XML File

<form-rules>

  <regexps>
    <regexp type="day"       
value="[1-9]|0[1-9]|[1-2][0-9]|3[0-1]"
message="error.jour"/>
    <regexp type="month"     
value="[1-9]|0[1-9]|1[0-2]" message="error.mois"/>
    <regexp type="year"      
value="[0-9][0-9][0-9][0-9]" message="error.annee"/>
    <regexp type="date"      
value="($day)-($month)-($year)" message="error.date"/>
    <regexp type="email"     
value="[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+"
message="error.email"/>
    <regexp type="int"        value="(^-?\d\d*$)"
message="error.int"/>
    <regexp type="minTwoLetter" value="...*"
message="error.minTwoLetter"/>
  </regexps>

  <form-beans>
    <form-bean type="com.cross.example.MyForm"
name="myForm">
      <property name="id"           regexp="$int"
notnull="true"/>
      <property name="firstname"   
regexp="$minTwoLetter" notnull="true"/>
      <property name="lastname"    
regexp="$minTwoLetter" notnull="(firstname!=null)"/>
      <property name="email"        regexp="$email"
notnull="true"/>
      <property name="birthday"     regexp="$date"/>
    </form-bean>

  </form-beans>
</form-rules>




 --- Andrej Sobkowski <as...@hotmail.com> a écrit :
> Hello All,
> 
> I have a set of design considerations/suggestions
> for the Validation 
> Framework in Struts. Let me know if I'm totally
> missing the point.
> 
> I like the whole Validator approach, in particular
> the XML configuration. I 
> believe that's the way to go, but I'd like to
> discuss a few points.
> 
> DISCUSSION: The Validator is quite "linked" to
> Servlet's stuff 
> (HttpServletRequest) and to FormBean. If I got it
> right, currently the 
> Validator needs a set of parameters to be passed to
> the ValidatorAction, 
> including the bean to validate, the Field and some
> Servlet parameters.
> 
> In a similar way, the validation process is linked
> to the FormBean 
> (validate() in FormBean class).
> 
> Shouldn't they be separate?
> - The Action should take care of the HTTP stuff
> while the Validator should 
> only have knowledge of the bean and the
> corresponding fields to be 
> validated.
> - The form bean itself is a "special data holder"
> and shouldn't be aware of 
> how its data is validated. Do you agree?
> 
> I was thinking at something like the following
> (pseudo-code):
> 
> * CONFIGURATION file (new DTD for struts-config.xml
> or separate file)
>   <action    path="/login"
>             
> type="com.mycompany.myActionWithValidation"
>              name="myForm">
>     <!-- add validation on myForm's property
> 'lastName' that will check via 
> a SizeValidator
>          that the size of the field is between 1 and
> 15 chars. If not, the 
> message will be
>          returned in the ValidationException (I18N
> can be added easily) -->
>     <validation property="lastName"
>                
> validator="com.mycompany.SizeValidator"
>                 arg0="1"
>                 arg1="15"
>                 message="Last Name is mandatory and
> can't be longer than 15 
> chars" />
>     ...
>   </action>
> 
> * JAVA CODE
> public interface IValidator(Object bean) {
>   +validate() throws ValidationException;
> }
> 
> public class Action {
>   ...
>   +addValidator(IValidator val)
>   +validators(): Iterator // returns an Iterator on
> all validators for the 
> action
> }
> 
> // Validator that checks if text size is >min and <
> max (for example).
> // It can be easily extended to check int min/max
> and so on.
> public class SizeValidator {
>   ... // min/max
> 
>   public void validate(Object bean) throws
> ValidationException {
>     Object value = getPropertyValue(bean);
>     if (value instanceof String) {
>       // Check String size
>       String check = (String)value;
>       if ((check.length() > maxSize) ||
>           (check.length() < minSize)) {
>           // Validation failed: throw exception
>           // with corresponding error message
> (defined in conf)
>           throwException(getValidationMessage());
>       }
>     } else {
>       // Error, wrong class type...
>     }
>   }
> }
> 
> 
> // Minor changes to ActionServlet
> public class ActionServlet {
>   ...
>   public void processInitValidatorsForAction(..) {
>   // By reading the XML configuration file, the
> ActionServlet will execute a 
> set of addValidator(..)
>   // For example, consider the following XML
> struts-config.xml (DTD to be 
> modified)
>   // <action
>   curAction.addValidator(new
> SizeValidator("lastName", "1", "15");
>   curAction.addValidator(new
> RegExpValidator("phone", "(999)999-9999");
>   ...
>   }
> 
>   // Executes all validators on FormBean(s) for
> action executed
>   public ActionErrors processValidate(...) {
>     Iterator it = action.validators();
>     try {
>       ((Validator)it.next()).validate(formBean); //
> the validator validates 
> the form bean only
>     } catch (ValidationException e) {
>       Log.debug("Validation failed!", e);
>       errors.addError(e.getMessage()); // Add
> multilanguage
>     }
>   }
> }
> 
> Useless to say, this is only a high-level point of
> view. It does work on my 
> prototype (no XML config), but it can be enhanced
> and optimized in many 
> ways. I think it's also conceptually pretty close to
> what is currently done 
> in the Validator.
> 
> The Validators can be designed as desired. To
> compare two values, simply 
> define a validator like CompareValidator(property1,
> property2, compareRule) 
> with compareRule = "<", ">",...
> 
> What do you think?
> 
> Thanks.
> 
> Andrej
> 
>
_________________________________________________________________
> Get your FREE download of MSN Explorer at
> http://explorer.msn.com/intl.asp
> 
> 
> --
> To unsubscribe, e-mail:  
> <ma...@jakarta.apache.org>
> For additional commands, e-mail:
> <ma...@jakarta.apache.org>
>  

___________________________________________________________
Do You Yahoo!? -- Une adresse @yahoo.fr gratuite et en français !
Yahoo! Courrier : http://courrier.yahoo.fr

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by Ted Husted <hu...@apache.org>.
I just want to make sure that everyone watching this thread is aware
that Struts does have a Validator, configured with an XML file, that
uses regular expressions or Javascript, and peforms that same
validations both client-side adn server-side, which many of us have been
using since April. It's available in the contrib folder in the Nightly
Build now, and at David Winterfeldt's Web site. 

http://home.earthlink.net/~dwinterfeldt/

This thread started when someone suggested we incorporate the validation
in the Action rather than the ActionForm. 

Reading some of these messages it's unclear to me what people are
suggesting that we are not doing now.


-- Ted Husted, Husted dot Com, Fairport NY USA.
-- Custom Software ~ Technical Services.
-- Tel +1 716 737-3463
-- http://www.husted.com/struts/

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by Ted Husted <hu...@apache.org>.
I just want to make sure that everyone watching this thread is aware
that Struts does have a Validator, configured with an XML file, that
uses regular expressions or Javascript, and peforms that same
validations both client-side adn server-side, which many of us have been
using since April. It's available in the contrib folder in the Nightly
Build now, and at David Winterfeldt's Web site. 

http://home.earthlink.net/~dwinterfeldt/

This thread started when someone suggested we incorporate the validation
in the Action rather than the ActionForm. 

Reading some of these messages it's unclear to me what people are
suggesting that we are not doing now.


-- Ted Husted, Husted dot Com, Fairport NY USA.
-- Custom Software ~ Technical Services.
-- Tel +1 716 737-3463
-- http://www.husted.com/struts/

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Validator design considerations

Posted by "emmanuel.boudrant" <b7...@yahoo.fr>.
This version more "readable" !

I'm working ont it, 

For validation, I suggest an external XML file based on regular expression, in this case we are able to generate and synchronise validator functions on client and server size. 

ex: 

****************************************** 
*Server size: (with project jakarta regexp) 

public ActionErrors validate (ActionMapping mapping, HttpServletRequest request) { 
ActionErrors errors=null; 
// Get the action errors by checking this instance and rules describe in 
// form-rules.xml 
try { 
errors = ReValidator.actionErrors(this); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
// Check others errors. Errors cannot be explain in form-rules.xml 
// Return errors. 
return errors; 
} 

************************************************ 
*Client side: 

<!-- Javascript validate function for check.do --> 
<script language="javascript"> 
function testField(field, regexp) { 
if ( field != null && field.value != "" && field.value != null) { 
var myRe = regexp.exec(field.value); 
if ( !myRe ) { 
return false; 
} else { 
return true; 
} 
} 
return true; 
} 

function validate() { 
var text=""; 
if ( document.myForm.email.value == "" || document.myForm.email.value == null ) text += ("email:*.\n"); 
else if ( !testField(document.myForm.email,/[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+/) ) 
text += ("email:[email invalide].\n") 
(...) 
if ( text == "" ) return true; 
alert("Erreur de saisie:\n\n" + text); 
return false; 
} 
</script> 

**************************************************** 
*And XML File 

<form-rules> 

<regexps> 
<regexp type="day" value="[1-9]|0[1-9]|[1-2][0-9]|3[0-1]" message="error.jour"/> 
<regexp type="month" value="[1-9]|0[1-9]|1[0-2]" message="error.mois"/> 
<regexp type="year" value="[0-9][0-9][0-9][0-9]" message="error.annee"/> 
<regexp type="date" value="($day)-($month)-($year)" message="error.date"/> 
<regexp type="email" value="[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+" message="error.email"/> 
<regexp type="int" value="(^-?\d\d*$)" message="error.int"/> 
<regexp type="minTwoLetter" value="...*" message="error.minTwoLetter"/> 
</regexps> 

<form-beans> 
<form-bean type="com.cross.example.MyForm" name="myForm"> 
<property name="id" regexp="$int" notnull="true"/> 
<property name="firstname" regexp="$minTwoLetter" notnull="true"/> 
<property name="lastname" regexp="$minTwoLetter" notnull="(firstname!=null)"/> 
<property name="email" regexp="$email" notnull="true"/> 
<property name="birthday" regexp="$date"/> 
</form-bean> 

</form-beans> 
</form-rules> 




--- Andrej Sobkowski <as...@hotmail.com> a écrit : > Hello All, 
> 
> I have a set of design considerations/suggestions 
> for the Validation 
> Framework in Struts. Let me know if I'm totally 
> missing the point. 
> 
> I like the whole Validator approach, in particular 
> the XML configuration. I 
> believe that's the way to go, but I'd like to 
> discuss a few points. 
> 
> DISCUSSION: The Validator is quite "linked" to 
> Servlet's stuff 
> (HttpServletRequest) and to FormBean. If I got it 
> right, currently the 
> Validator needs a set of parameters to be passed to 
> the ValidatorAction, 
> including the bean to validate, the Field and some 
> Servlet parameters. 
> 
> In a similar way, the validation process is linked 
> to the FormBean 
> (validate() in FormBean class). 
> 
> Shouldn't they be separate? 
> - The Action should take care of the HTTP stuff 
> while the Validator should 
> only have knowledge of the bean and the 
> corresponding fields to be 
> validated. 
> - The form bean itself is a "special data holder" 
> and shouldn't be aware of 
> how its data is validated. Do you agree? 
> 
> I was thinking at something like the following 
> (pseudo-code): 
> 
> * CONFIGURATION file (new DTD for struts-config.xml 
> or separate file) 
> <action path="/login" 
> 
> type="com.mycompany.myActionWithValidation" 
> name="myForm"> 
> <!-- add validation on myForm's property 
> 'lastName' that will check via 
> a SizeValidator 
> that the size of the field is between 1 and 
> 15 chars. If not, the 
> message will be 
> returned in the ValidationException (I18N 
> can be added easily) --> 
> <validation property="lastName" 
> 
> validator="com.mycompany.SizeValidator" 
> arg0="1" 
> arg1="15" 
> message="Last Name is mandatory and 
> can't be longer than 15 
> chars" /> 
> ... 
> </action> 
> 
> * JAVA CODE 
> public interface IValidator(Object bean) { 
> +validate() throws ValidationException; 
> } 
> 
> public class Action { 
> ... 
> +addValidator(IValidator val) 
> +validators(): Iterator // returns an Iterator on 
> all validators for the 
> action 
> } 
> 
> // Validator that checks if text size is >min and < 
> max (for example). 
> // It can be easily extended to check int min/max 
> and so on. 
> public class SizeValidator { 
> ... // min/max 
> 
> public void validate(Object bean) throws 
> ValidationException { 
> Object value = getPropertyValue(bean); 
> if (value instanceof String) { 
> // Check String size 
> String check = (String)value; 
> if ((check.length() > maxSize) || 
> (check.length() < minSize)) { 
> // Validation failed: throw exception 
> // with corresponding error message 
> (defined in conf) 
> throwException(getValidationMessage()); 
> } 
> } else { 
> // Error, wrong class type... 
> } 
> } 
> } 
> 
> 
> // Minor changes to ActionServlet 
> public class ActionServlet { 
> ... 
> public void processInitValidatorsForAction(..) { 
> // By reading the XML configuration file, the 
> ActionServlet will execute a 
> set of addValidator(..) 
> // For example, consider the following XML 
> struts-config.xml (DTD to be 
> modified) 
> // <action 
> curAction.addValidator(new 
> SizeValidator("lastName", "1", "15"); 
> curAction.addValidator(new 
> RegExpValidator("phone", "(999)999-9999"); 
> ... 
> } 
> 
> // Executes all validators on FormBean(s) for 
> action executed 
> public ActionErrors processValidate(...) { 
> Iterator it = action.validators(); 
> try { 
> ((Validator)it.next()).validate(formBean); // 
> the validator validates 
> the form bean only 
> } catch (ValidationException e) { 
> Log.debug("Validation failed!", e); 
> errors.addError(e.getMessage()); // Add 
> multilanguage 
> } 
> } 
> } 
> 
> Useless to say, this is only a high-level point of 
> view. It does work on my 
> prototype (no XML config), but it can be enhanced 
> and optimized in many 
> ways. I think it's also conceptually pretty close to 
> what is currently done 
> in the Validator. 
> 
> The Validators can be designed as desired. To 
> compare two values, simply 
> define a validator like CompareValidator(property1, 
> property2, compareRule) 
> with compareRule = "<", ">",... 
> 
> What do you think? 
> 
> Thanks. 
> 
> Andrej 
> 
> _________________________________________________________________ 
> Get your FREE download of MSN Explorer at 
> http://explorer.msn.com/intl.asp 
> 
> 
> -- 
> To unsubscribe, e-mail: 
> <ma...@jakarta.apache.org> 
> For additional commands, e-mail: 
> <ma...@jakarta.apache.org> 
> 



---------------------------------
Yahoo! Courrier -- Une adresse @yahoo.fr gratuite et en français !