public static void main()

in src/example/org/apache/commons/validator/example/ValidateExample.java [61:126]


    public static void main(String[] args)
        throws ValidatorException, IOException, SAXException {
            
        InputStream in = null;
        ValidatorResources resources = null;
        
        try {
        
            // Create a new instance of a ValidatorResource, then get a stream
            // handle on the XML file with the actions in it, and initialize the
            // resources from it.  This would normally be done by a servlet
            // run during JSP initialization or some other application-startup
            // routine.
            in = ValidateExample.class.getResourceAsStream("validator-example.xml");
            resources = new ValidatorResources(in);
            
        } finally {
            // Make sure we close the input stream.
            if (in != null) {
                in.close();
            }
        }
        
        // Create a test bean to validate against.
        ValidateBean bean = new ValidateBean();
        
        // Create a validator with the ValidateBean actions for the bean
        // we're interested in.
        Validator validator = new Validator(resources, "ValidateBean");
        
        // Tell the validator which bean to validate against.
        validator.setParameter(Validator.BEAN_PARAM, bean);
        
        ValidatorResults results = null;
        
        // Run the validation actions against the bean.  Since all of the properties
        // are null, we expect them all to error out except for street2, which has
        // no validations (it's an optional property)
        
        results = validator.validate();
        printResults(bean, results, resources);
        
        // Now set all the required properties, but make the age a non-integer.
        // You'll notice that age will pass the required test, but fail the int
        // test.
        bean.setLastName("Tester");
        bean.setFirstName("John");
        bean.setStreet1("1 Test Street");
        bean.setCity("Testville");
        bean.setState("TE");
        bean.setPostalCode("12345");
        bean.setAge("Too Old");
        results = validator.validate();
        printResults(bean, results, resources);
        
        // Now only report failed fields
        validator.setOnlyReturnErrors(true);
        results = validator.validate();
        printResults(bean, results, resources);
        
        // Now everything should pass.
        validator.setOnlyReturnErrors(false);
        bean.setAge("123");
        results = validator.validate();
        printResults(bean, results, resources);
    }