Validating framework

HI
can we we use server side validation framework in struts and validate() method in form.
I used both but only server side validate framework works.
can u suggest how to use vaildate method also.
here is the code what i have done
register.jsp
     <body>
          <html:form action="regs.do" method="post">          
          <bean:message key="user" />
               <html:text property="userid" />
               <html:errors property="userid" />
               <br>
               <bean:message key="pass" />
               <html:password property="password" />
               <html:errors property="password" />
               <br>
               <html:submit value="Submit" />
          </html:form>
     </body>
</html>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<data-sources />
<form-beans>
     <form-bean name="regForm" type="com.forms.RegistrationForm" />
</form-beans>
<global-exceptions />
<global-forwards>
     <forward name="start" path="/register.jsp" />
</global-forwards>
<action-mappings>
     <action path="/regs" type="com.actions.RegistrationAction" name="regForm" scope="request" validate="true" input="/register.jsp">
          <forward name="success" path="/success.jsp" />
          <forward name="failure" path="/failure.jsp" />
     </action>
</action-mappings>
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
<!-- validator framework plugin -->
     <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
     <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
     </plug-in>     
</struts-config>
ApplicationResources.properties
errors.required={0} is required as said rama.
RegistrationForm .java
package com.forms;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;
public class RegistrationForm extends ValidatorForm {     
     protected String userid;
     protected String password;
     public String getPassword() {
          return password;
     public void setPassword(String password) {
          this.password = password;
     public String getUserid() {
          return userid;
     public void setUserid(String userid) {
          this.userid = userid;
     public ActionErrors validate(ActionMapping map,HttpServletRequest req){
          ActionErrors errors=new ActionErrors();
          if(this.password==null ||this.password == "" ||this.userid==null ||this.userid== ""){
               errors.add("userid",new ActionError("this is rama"));
          return errors;
validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">
<form-validation>
     <formset>
          <form name="regForm">
               <field property="userid" depends="required">
                    <arg0 key="some.userid"/>
               </field>
               <field property="password" depends="required">
                    <arg0 key="some.password"/>
               </field>          
          </form>
     </formset>
</form-validation>

I think you could still use the validator form.
You say you have 10 fields on your form, up to 3 of which are visible?
Its a bit of a hack, but what it would require is 10 hidden fields on the page. One for each of the controls. The hidden field value would be set if the control was meant to be present, and empty if not.
That way the validWhen syntax only has to deal with two fields
1 - a hidden field indicating whether or not to validate
2 - the field to validate itself.
You just have to set the values of the hidden fields according to which controls you are showing/hiding.
An alternative:
Use ValidatorActionForm rather than just ValidatorForm.
ValidatorActionForm fires on a specific "action" rather than a specific "form"
ie it uses the name of the action to choose which validation to run rather than the name of the form
You would then have to define seperate ACTIONS in struts-config for each of the variations of the page, and validation for each action, but you would still only have one jsp page and one Action class as they could all be the same.
Cheers,
evnafets

Similar Messages

  • Dyna Form +Validator Framework--- peculair problem with java.lang.Integer

    In my struts application , i m using Dyna Action form,and Validator framework
    <form-bean
    name="myDynaForm"
    type="org.apache.struts.validator.DynaValidatorForm">
    <form-property name="name" type="java.lang.String"/>
    <form-property name="phoneNo" type="java.lang.Integer"/>
    </form-bean>
    Now if user does not enter name , then a error meassage is dispalyed,
    and aslo this time phoneNo shows 0.
    why 0 is displayed here?
    Can anybody tell me

    Hi all,
    If my memory serves me well, the exception is thrown because the application needs a working calendar for a person provided in time mangement. Make sure the correct infotypes are used. Also the organization structure needs to be set up correctly. The manager needs someone to approve and the employee needs someone to get approved by.
    Regards, Marcel.

  • Client side validation in struts using validation framework

    Hi ,
    am new to struts.....
    I want to validate a simple login page using struts validation framework...
    For that i created,
    login.jsp ( contains html:errors and html:javascript and onsubmit)
    LoginForm extends ValidatorForm
    LoginAction
    resource bundles
    validation.xml ( required, minlength and maxlength rules for both fields)
    struts-config.xml ( configured action mapping and form beans)
    whats my problem is....
    i will get error messages through server side validation...
    i cant able to get the error messages using javascript i.e alert messages.
    i seen the page resource in that all javascript functins are inserted.
    on seeing the javascript error console... it shows
    formName has no properties...............
    exactly at this line
    oRequired = eval('new ' + formName.value + '_required()'); //function validateRequired(form)

    Thanks for your valuable reply.....
    Ya of course what you said was correct....
    I got error messages while submitting the form without any value....
    error messages are displayed using the <html:errors/> tag (server side validation ).
    But it fails to show the alert messages for those errors ( client side validation).
    i inserted the <html:javascript formName="form bean name" /> tag in the bottom of my login jsp.....
    on seeing the error console, it shows formName has no properties.
    Could anybody help me to sort out this problem........

  • Integrate struts validator framework

    (JHeadstart 9.0.4: Toplink/JSP/Struts)
    I am trying to integrate the struts validator framework . I'm encountering the following
    problem. When a validation rule(defined in the struts validation.xml) is violated I would expect
    that the JSP include named jhsInfo.jsp would show the errormessage because I assumed that it also
    reads from the same Error Bean (ActionErrors object ) struts normally uses.
    When I include a jsp of my own, containing the following:
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <html:errors/>
    then messages raised by the struts validation framework are shown and everything seems to work.
    I have the following questions:
    - Is it possible to show struts validation error messages using the jhsInfo.jsp ?
    I investigated the <jhs:ifContainsError> in the JHeadstart Taglibrary
    and noticed how it checks for the JHS_USER_INFO session attribute; apparently, when the validate()
    method in JhsDynaActionForm finds ActionErrors through the Struts Validator framework, this session attribute is not set.
    However, even if we add this attribute explicitly to sessionData in validate(), we do not get the Struts Validator Action Errors.
    - If not possible, how could we adapt the code to make it work? Should we instantiate JHeadstart UserExceptions
    for all ActionErrors or does JHeadstart have built-in functionality to deal with these ActionErrors in the proper way?
    Are we running into a bug, is it intentional to keep Struts Validator Error separate from JHeadstart Exception Errors
    or is JHeadstart currently not equipped with the logic to deal with the ActionErrors?
    Thanks in advance,
    Rob Brands (Amis)

    Rob,
    JHeadstart transforms UserExceptions (controller-independent) to Struts specific ActionErrors and ActionMessages in JhsRequestprocessor.convertUserExceptions.
    So, with JHeadstart you can either use ACtionErrors/ActionMessages directly, or indirectly by thrwoing UserExceptions.
    In jhsInfo we use html:messages to loop over both messages and errors (The boolean attribute message determines whether ActionErrors or ActionMessages are iterated). We do not use html:errors because that does not provide you with control over the layout of individual messages.
    You are right that our custom tags ifContainsError and ifContainsInformation should also directly check for existence of ActionErrors and ActionMessages. We will fix that for the upcoming release.
    With that fix in place, you should be able to use jhsInfo.jsp to display validator messages.
    You mentioned you tried to put a "dummy" JHS_USER_INFO exception on the session in the validate() method. This approach should work, however, to display ActionErrors (as is the case with the validator framework), you should use JHS_USER_ERROR as the key, noy JHS_USER_INFO.
    For now, you could choose to modify jhsInfo.jsp and use your own ifContains tags, until we have fixed this.
    Steven Davelaar.

  • Validation Framework & xsd:include

    I'm having some problems using the new Validation Framework with schemas that have <xsd:include> dependancies.
    Assume this schema (TestSchema.xsd):
    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
         <xsd:include schemaLocation="TestInclude.xsd"/>
         <xsd:element name="RootElement">
              <xsd:complexType>
                   <xsd:sequence>
                        <xsd:element name="SubElement1" type="xsd:string"></xsd:element>
                        <xsd:element name="SubElement2" type="xsd:string"></xsd:element>
                        <xsd:element ref="IncludedElement"/>
                   </xsd:sequence>
              </xsd:complexType>
         </xsd:element>
    </xsd:schema>...Which relies on this dependancy (TestInclude.xsd)
    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
         <xsd:element name="IncludedElement" type="xsd:string"></xsd:element>
    </xsd:schema>And a simple document based on this Schema (TestDoc.xml)
    <?xml version="1.0" encoding="UTF-8"?>
    <RootElement>
      <SubElement1>Hello</SubElement1>
      <SubElement2>World</SubElement2>
      <IncludedElement>Include me too!</IncludedElement>
    </RootElement>My validation code looks like this:
    public class ValidatorTest
         public ValidatorTest()
              SchemaFactory factory = SchemaFactory.newInstance(
                        XMLConstants.W3C_XML_SCHEMA_NS_URI);
              StreamSource source = new StreamSource(
                        getClass().getResourceAsStream("/TestSchema.xsd"));
              StreamSource includeSource = new StreamSource(
                        getClass().getResourceAsStream("/TestInclude.xsd"));
              Schema schema;
              try
    //By the javadocs, this is the proper way of compiling schemas w/ dependancies
                        schema = factory.newSchema(new StreamSource[]{includeSource,source});
                        System.out.println("Schema compiled.");
                        Validator v = schema.newValidator();
                        StreamSource document = new StreamSource(getClass().getResourceAsStream("/TestDoc.xml"));
                        v.validate(document);
                        System.out.println("Document validated.");
                   catch(Exception ex)
                        ex.printStackTrace();
         }This schema compiles correctly (I see my first log message). But an exception occurs when I call v.validate(document).
    Cannot find the declaration of element 'RootElement'.
    I should also point out that this code works when I test against an xsd that doesn't have an external dependancy.
    Any advice?

    Sigh
    Looks like this is a bug.
    Sigh

  • Java Validation Framework

    Hi,
    Is there any Validation Framework avail for validating a Form,i am expecting this framework will be a plugin,so i can change the validation at any time,without building the application everytime, so we can configure different validations for different projects, without changing the build.
    I searched the net & find out Rule Engine ( Ex: Drools ) can do this, is there any other framework available..?
    Thx.

    There is the general Java validation JSR, of which [Hibernate Validator|http://www.hibernate.org/subprojects/validator.html] is a populate implementation. Your actual MVC framework also undoubtedly has a validator API.
    - Saish

  • Struts validation framework not working

    Hi
    I created a very simple webapp and using struts validation framework. But, it always give me validation errors even i filled out all the required firled information. i have my struts-config included the plug-in, points to the location of validation.xml & validation-rule.xml, and i have the validate set to true, and an input point to the page when validation fails, plus my formbean to extend the validatorForm. But, no matter what, it always pass the validation. in other words, the validate method in the validator always returns 0 errors. Any ideas what might be wrong? or any suggestions of how i can debug it?
    Thanks a lot.
    cc

    There is an bug in Sun One App Server
    U need to add permission for delete in the server policy file
    please refer to
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803631

  • Validation Framework

    Is there a validation frame work available in JavaFX 2.0.3 FXML?
    I have a requirement to validate an email address entered in a text field.
    I am thinking about having a label defined in defined in my controller and set the appropriate text when some validation fails.
    For Eg:
    public class LoginController {
        @FXML private TextField studentId;
        @FXML private PasswordField password;
        @FXML private Label errorMessage;
        @FXML protected void processLogin(ActionEvent event) {
            if(!isValidEmail(studentId)){
                errorMessage.setText("Invalid email Id: " + studentId.getText());
    }and my FXML:
    <children>
          <Label text="Student::" />     
          <TextField fx:id="studentId" />
          <Label text="Password:" />     
          <PasswordField fx:id="password" />
          <Button text="login" defaultButton="true" fx:id="login" onAction="#processLogin"/>
          <Label layoutX="80.0" layoutY="200.0" textFill="RED" fx:id="errorMessage" />
    </children>
    .... .... .... ....Is this the best way or is there a better way to handle validations in FXML? Any inputs are highly appreciated.
    Thanks.

    Ask Daniel to get busy and finish implementing and documenting this for his jfx-flow framework ;-)
    http://www.zenjava.com/jfx-flow/
    Here are some related discussion threads:
    http://mail.openjdk.java.net/pipermail/openjfx-dev/2011-December/000048.html
    http://mail.openjdk.java.net/pipermail/openjfx-dev/2012-February/000717.html
    Re: Forms and validations - here's some of my ideas, what are yours?

  • Struts validation framework

    Dear all,
    To use struts validator, I should make my action form to extend
    org.apache.struts.validator.action.ValidatorForm instead of org.apache.struts.action.ActionForm.
    However, I have to also make my action form to extend a third part action form which extends org.apache.struts.action.ActionForm.
    In this case, how can I continue to use Struts validator without changing the third part code?
    Pengyou

    You can use the java script for checking this.
    for (i=0;i<Form.elements.length;i++) {
    //alert("Elements Type: " + Form.elements.type);
    if (Form.elements[i].type == "checkbox") {
              checkBoxCounter++;
              if (Form.elements[i].checked) {
                   alert("Checked Name is .! " + Form.elements[i].name);
                   alert("Checked Id is .! " + Form.elements[i].id);
              }//End of if (Form.elements[i].checked)
    }// End of if (Form.elements[i].type == "checkbox"
    }// End of for (i=0;i<Form.elements.length;i++)

  • Struts validator framework

    i need script to validate more than two fields using struts validator ,it is possible

    a submit button is also an form input element, so it's sended as all the other form input elements.
    Suppose you have these two buttons:
    <input name="submit1" type="submit" value="submit1">
    <input name="submit2" type="submit" value="submit2">In your struts validator (server side), check what button submit was used:
    String submit1 = request.getParameter("submit1");
    String submit2 = request.getParameter("submit2");
    if(submit1!=null){
    }NB: if you are using FormBean, so add twoextra atributes for the two submit inputs and don't forget to bind them in your jsp. In this case, check twhat submit button was used like the following :
    if(yourFormBean.getSubmit1()!=null&&"submit1".equals(yourFormBean.getSubmit1())){
    }else if(yourFormBean.getSubmit2()!=null&&"submit2".equals(yourFormBean.getSubmit2())){
    }Hope That Helps

  • Struts validation framework  doubt:

    hi
    in "validation-rules.xml" if we have both "class reference that implementing a rule" and "java script"
    JavaScript validations are provided when enabled,
    and server-side validations are guaranteed.
    if we enable javascript validations then there may be possibility of both client side validations,serverside validations on same field .is my understanding is correct or when javascripts validations are enabled,are they going to stop further serverside validations.

    You understanding is correct.
    The javascript validation will happen if the client is javascript enabled.
    The server side validation will always happen.
    There are just too many ways to trick javascript, or fake a form submission.
    The server will ALWAYS validate everything.
    The advantage provided by javascript is that the validation can be done on the client, thus saving a network round trip to tell the user that they are an idiot ;-)
    Cheers,
    evnafets

  • Schema Validation Framework - Compiling Schema

    While trying to compiling the Schema fiel, I am getting this error.
    java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchem
    I am getting error in this piece of Code
    public static Schema compileSchema(String schema) throws SAXException{
            //Get the SchemaFactory instance which understands W3C XML Schema language
             SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            return sf.newSchema(new File(schema));
        }I have copied sax.jar,dom,xalan and xercesImple jar files to JAVA_HOME/lib/endorsed directory. I also tried copying jaxp-api.jar but that didn't work too.
    ( I am using jaxp 1.3 (from jwsdp 1.6) with jdk 1.4 )
    Not sure what else am I missing that's causing the error.
    Please help.

    Please help...I have ran out of options and have spent too much of time figuring out the problem. I really need to resolve this soon.
    (Sorry for couple of spelling mistakes on my side in the original post)

  • How to use the validation.xml in struts validation?

    Can any one please help me, how to use the validation.xml in struts validation? possible please give me simple example.
    Edited by: SathishkumarAyyavoo on Jan 31, 2009 12:03 PM

    These 2 are the good articles for the beginners to do validation things in Struts. you can follow any one of them.
    1. [http://viralpatel.net/blogs/2009/01/struts-validation-framework-tutorial-example-validator-struts-validation-form-validation.html]
    2. [http://www.vaannila.com/struts/struts-example/struts-custom-validation-example-1.html]
    All the best.

  • What is your strategy for form validation when using MVC pattern?

    This is more of a general discussion topic and will not necessarily have a correct answer. I'm using some of the Flex validator components in order to do form validation, but it seems I'm always coming back to the same issue, which is that in the world of Flex, validation needs to be put in the view components since in order to show error messages you need to set the source property of the validator to an instance of a view component. This again in my case seems to lead to me duplicating the code for setting up my Validators into several views. But, in terms of the MVC pattern, I always thought that data validation should happen in the model, since whether or not a piece of data is valid might be depending on business rules, which again should be stored in the model. Also, this way you'd only need to write the validation rules once for all fields that contain the same type of information in your application.
    So my question is, what strategies do you use when validating data and using an MVC framework? Do you create all the validators in the views and just duplicate the validator if the exact same rules are needed in some other view, or do you store the validators in the model and somehow reference them from the views, changing the source properties as needed? Or do you use some completely different strategy for validating forms and showing error messages to the user?

    Thanks for your answer, JoshBeall. Just to clarify, you would basically create a subclass of e.g. TextInput and add the validation rules to that? Then you'd use your subclass when you need a textinput with validation?
    Anyway, I ended up building sort of my own validation framework. Because the other issue I had with the standard validation was that it relies on inheritance instead of composition. Say I needed a TextInput to both check that it doesn't contain an empty string or just space characters, is between 4 and 100 characters long, and follows a certain pattern (e.g. allows only alphanumerical characters). With the Flex built in validators I would have to create a subclass or my own validator in order to meet all the requirements and if at some point I need another configuration (say just a length and pattern restriction) I would have to create another subclass which duplicates most of the rules, or I would have to build a lot of flags and conditional statements into that one subclass. With the framework I created I can just string together different rules using composition, and the filter classes themselves can be kept very simple since they only need to handle a single condition (check the string length for instance). E.g. below is the rule for my username:
    library["user_name"] = new EmptyStringFilter( new StringLengthFilter(4,255, new RegExpFilter(/^[a-z0-9\-@\._]+$/i) ) );
    <code>library</code> is a Dictionary that contains all my validation rules, and which resides in the model in a ValidationManager class. The framework calls a method <code>validate</code> on the stored filter references which goes through all the filters, the first filter to fail returns an error message and the validation fails:
    (library["user_name"] as IValidationFilter).validate("testuser");
    I only need to setup the rule once for each property I want to validate, regardless where in the app the validation needs to happen. The biggest plus of course that I can be sure the same rules are applied every time I need to validate e.g. a username.
    The second part of the framework basically relies on Chris Callendar's great ErrorTipManager class and a custom subclass of spark.components.Panel (in my case it seemed like the reasonable place to put the code needed, although perhaps extending Form would be even better). ErrorTipManager allows you to force open a error tooltip on a target component easily. The subclass I've created basically allows me to just extend the class whenever I need a form and pass in an array of inputs that I want to validate in the creationComplete handler:
    validatableInputs = [{source:productName, validateAs:"product_name"},
                         {source:unitWeight, validateAs:"unit_weight", dataField:"value"},
                   {source:unitsPerBox, validateAs:"units_per_box", dataField:"value"},
                        {source:producer, validateAs:"producer"}];
    The final step is to add a focusOut handler on the inputs that I want to validate if I want the validation to happen right away. The handler just calls a validateForm method, which in turn iterates through each of the inputs in the validatableInputs array, passing a reference of the input to a suitable validation rule in the model (a reference to the model has been injected into the view for this).
    Having written this down I could probably improve the View side of things a bit, remove the dependency on the Panel component and make the API easier (have the framework wire up more of the boilerplate like adding listeners etc). But for now the code does what it needs to.

  • How do you create custom validation rule in WS 9.2?!?!?!

    Hello,
    I am using Workshop 9.2. I created a page flow, and want to do some form validations.
    I saw the simple 9.2 example, but it is only good for very basic validation, what if you have to validate the form field against a database, must you write a custom validation rule? HOW would you do this in 9.2 so that will still stay with the workshop/netui paradigm?
    http://beehive.apache.org/docs/1.0.1/netui/validation.html
    Keith

    Hi Keith,
    Staying within the declarative validation framework the answer is probably that you do need to write a custom validation rule and refer to it using the @Jpf.ValidateCustomRule annotation.
    The NetUI Annotation Reference shows how the Struts validations are supported via the framework.
    http://beehive.apache.org/docs/1.0.1/netui/annotations/pageflow_annotations.html
    Specifically, if you look through the @Jpf.Validate* annotations, while most of these are "canned" common validations, there are a few that are more open-ended, such as @Jpf.ValidateMask and @Jpf.ValidateValidWhen.
    Those two let you write the validation logic in the annotation while @Jpf.ValidateCustomeRule only refers to a custom rule in the struts validator file.
    In any case, there is a validation rule editor which should help in authoring and managing the annotations. In the Page Flow Explorer or Page Flow Editor just right click on the action or form bean bean of interest and choose Validation Rules and the appropriate scope.
    I hope that's of some use,
    Troy

Maybe you are looking for

  • How to get individual messages in Mac Mail???

    In Mavericks when I get mail from the same email address it groups it all under one option so I sometimes miss the mail. How can I get it so that each message is individual and not grouped into a folder under one email address?

  • How do I change the width of column "rating"

    all columns are variable in widht. but not "rating" (stars). How do I change the width of column "rating"?

  • "Safari quit unexpectedly" Error message. I cannot reopen Safari at all

    I can no longer open Safari.  Get error message "Safari quit unexpectedly" I cannot reopen Safari.  Read article on removing malware and removed tuneupmymac, still can't open

  • Is my EHD dying?

    Today I decided to do the Erase Free Space procedure in Disk Utility on my internal hard drive. I'm not sure if that is relevant to my problem, but it coincides at least. Just after I got started with that, I got this error message. "My Book 2011" is

  • SQL Error: ORA-01873: the leading precision of the interval is too small

    Hi, My requirement is to get the current time stamp in Epoch time microsec format. I am trying to execute the following query select (CAST(((current_timestamp - TO_DATE('01/01/1970 00:00:00', 'MM-DD-YYYY HH24:MI:SS'))*24*60*60*1000000) AS varchar(32)