Jakarta Commons Validator
Section 01 Validator Total Overview
Each application is responsible for ensuring that the data they are inserted into the latter library is legally effective. After all, if the data relying on these applications is destroyed, it will be disastrous. What can I take anything? Come to make yourself working properly? For example, an application using a regular relational database, each field in the database has its own rules and constraints to ensure that the data stored in it is properly correct. Any application of the Taiwan-funded material database data is responsible for protecting the integrity of the data they submitted. Any operation attempts to insert or update data that does not meet the standard may be discovered and rejected. This detection may be spread throughout the entire application, and there may be some verification in the performance layer, and the business logic layer, the business logic object is generally verified, and the data is also checked in the post-Taiwan investment. Unfortunately, since this verification is ubiquitous in the application, it has caused code redundancy of applications to a certain extent. This is not what the app is hoped because this repetitive labor is repeated in a plurality of times, making the application deployment and maintenance take more time. If these validation rules can be reused throughout the app, they will make the application more flexible. In other words, the deployment is faster, the customization is easier, and the program is more flexible. Jakarta Commons Project Validator Framework Introduction Validator is an open source project created by David Winterfeldt, which is also a sub-project for Jakarta Commons. The Commons project is primarily providing some reusable components like Validator. Other well-known Commons components are as BeanUtils, Digester, Logging frameworks, and more. Validator version 1.0 was posted in early November 2002. Use the benefits of Validator. Use the Validator framework to define a lot of advantages than the average verification rules in the application's code, such as: You can define a verification rule for the application;. Verification rules and applications are loose coupling; The server-side and client authentication rules can be defined at the same point; configure new verification rules or modify existing validation rules become simpler; support international; support regular expressions; can be used for web applications Standard Java application; use declarative method to implement rather than programming; except, Validator's largest feature is its own support of pluggability. Behind the article you will see the verification rules built in the Validator framework to better complete your work, and more importantly, the Validator Framework allows you to customize the authentication program and insert them into the frame. The relationship between Struts and Validator should point out that the Validator framework itself is built due to the Struts framework. Validator's creator David Winterfeldt discovered in the process of using Struts, which requires repeated use of the same verification rule in many ACTIONForm classes, which causes a lot of code redundancy. So he decided to create a Validator framework to eliminate this redundancy, so that Validator was born. Although the Validator architecture was originally born for the Struts architecture, it was still designed and configured to be used separately from the Struts architecture. This feature allows you to use this frame in any application, don't take it to the Struts architecture. It doesn't affect your application role because you don't use the Struts framework. In fact, this is why Validator is part of the Jakarta Commons project and is not part of the Struts project.
Now let's integrate this framework to web applications like the Struts architecture. In the final midth of the article, we will show how to apply it to other types of applications, such as EJB-based applications. Validator Component Overview The Validator architecture has the following components: validators; profiles; resource binding; JSP custom labels; validator form; What is Validators? A Validator is a Java class when performing a validator frame. The framework calls this Validaotor class based on the method defined in the configuration file. In general, each Validator class provides a separate verification rule, and then these rules can be combined into a more complex rule set. Validate verification, this matter, writing procedure is very important, you must first determine if the data is correct, so that the action or event will continue, then write the same verification mode each time, it is better to pass the JavaBean data verification XML settings, if the correct verification is successful, an error is a validation. For people who have not used Bean Validation, they can be a bit, but they may have a little effort, but they may understand it. The latest version is V1.0.2 Binary Download Source Download this time, download this time, please download Source Because there are many sample programs in it. Section 02 Basic examples You can view org.apache.commons.validator.example. * file, is very simple, only validateexample.java and ValidateBean.java, these two programs, and Validator-Example.xml is used as a Bean's verification setting. Also ApplicationResources.properties is setting multiple languages (i18n) You can directly refer to ValidateExample, setting the Validator method is very simple.
Establish ValidatorResource Instance and obtain a verification profile
ValidatorResources Resources = New ValidatorResources ();
IN = validateexample.class.getResourceceasstream ("Validator-Example.xml);
ValidatorResourcesInitializer.Initialize (resources, in);
Javabean to be verified
ValidateBean bean = new validatebean ();
Establish a verifier, and inform which JavaBean needs to be verified
Validator Validator = New Validator (Resources, "ValidateBean");
Validator.AddResource (Validator.Bean_Key, Bean);
Establish a verification result storage area, put the verification result into
ValidatorResults Results = NULL;
Results = validator.validate ();
ValidatorResults is a HashMap stored ValidateResult, which is in accordance with Property as Key,
ValidatorResult Result = results.getvalidatorResult (propertyName);
Remove the validatorResult; then use isvalid () Method to determine whether the verification is successful.
Section 03 Validator-Example.xml
Wherever Global is notified, various situations need to use the Validator to judge, and set the error message, refer to the contents of ApplicationResource.properties to display, and the Form's judgment mode can be placed in the name of the display, "Errors.Required = The {0} Field is Required." If the verification fails, NameForm.Firstname.DisplayName will replace {0} in the Properties of the first name in Properties, the method of replacing {0} Important is Method such as Public Static Boolean Validatexxxxx (Object Bean, Field Field)
Public class testValidator {
/ **
* Checks if the field is required.
*
* @Param Value The Value Validation is Being Performed ON.
* @Return Boolean if The Field isn't Null and
* Has a Length Greater Than Zero,
* True is returned.
* OtherWise False.
* /
Public Static Boolean ValidateRequired (Object Bean, Field Field) {
String value = value = validatorutil.getValueAsstring (bean, field.getproperty ());
Return! GenericValidator.isblankornull (Value);
}
}
Section 05 GenericValidator is currently genericvalidator
Isblankornull (Java.lang.String Value): Check if it is null value, and if the length is larger than zero isbyte (java.lang.string value): Whether it can be converted to byte iscreditcard (java.lang.string value): To the correct credit card isdate (java.Lang.Locale Locale): Whether it is a valid date, you can judge Isdate (java.lang.string value, java.lang.string value, java.lang.string value, java.lang.string value, java.lang.string value, java.lang.string datepattern, boolean Strict): Whether is a valid date, you can enter the date format, you need to fully comply with IsDouble (Java.lang.String Value): Whether you can turn to Double ISemail (Java.lang.String Value): Whether is a valid Email Isfloat ( Java.lang.string value): Whether you can turn into Float Isinrange (Double Value, Double Min, Double Max): Enter the value in this section (Double) Isinrange (Float Value, Float Min, Float Max): Your value is This section (FLOAT): Int Value, Int min, int max: Enter the value in this section (int) is ISINRANGE (Short Value, Short Min, Short Max): Enter the value in this section (SHORT) ISINT (Java .lang.string value): Whether you can convert to int islong (java.lang.string value): Can I turn into long isshort (java.lang.string value): Can I turn into Short MatchRegeXP (Java.lang.String Value) Java.lang.string regexp): Whether it meets the entered Regular Expression Maxlength (java.lang.str ING VALUE, INT MAX: The length is not greater than the input value minlength (java.lang.string value, int min): The length is not less than the input value I think the best use is MatchRegexp to set a variety of judgment .SECTION 06 Struts Validator originally earliest, struts-validate is
Http://home.earthLink.net/~dwinterfeldt/revision.html begins here, 2002 starts using Commons-Validator, transfer to Jakarta to continue development, you will find that commuts developers .
Struts-config.xml can be set through Plug-in Struts
Property = "pathnames" Value = "/ Web-inf / validator-rules.xml, / web-inf / value.xml" /> plug-in> ValidatorPlugin.java is a servlet that implements Plugin ("INIT ()" & "Destroy ()") Public Class ValidatorPlugin Implements Plugin {Public Void INIT (ActionServlet Servlet, ModuleConfig Config) Throws servletexception { ...... InitResources (); ...... } Protected void initress () throws oException, servletexception { ...... ValidatorResourcesInitializer.Initialize (Resources, Bis, False); ...... } Public void destroy () { ..... } } ValidatorResourcesInitializer is a component belonging to Commons-Validator, and the additional /Web-inf/Validator-Rules.xml contains the verification of the Client side JavaSCIRPT, and the verification of the Commons-Validator. The last /web-inf/validation.xml, that is For FormBean to verify, of course, you can use Commons-Validator to verify for ValueObject. Section 07 Summary If you don't work with the EIS (DB Layer) level, you can write yourself through the Validator standard for the input data. The company's business logic Validator. I will give an example statement. Import javax.servlet.http.httpservletRequest; import org.apache.commons.validator.Field; import org.apache.commons.validator.GenericValidator; import org.apache.commons.validator.ValidatorAction; import org.apache.commons.validator.ValidatorUtil; import org.apache.struts .action.ActionErrors; import org.apache.struts.validator.Resources; import java.text.SimpleDateFormat; import java.text.ParsePosition; import java.util.Date; import org.apache.commons.lang.StringUtils; import org .apache.struts.validator.fieldchecks; import org.apache.commons.logging.logfactory; import org.apache.commons.logging.log; / ** * ValidationUTIL HELPER CLASS for Performing Custom Validations That * Aren't Already Included in The Core Struts Validator. * * * View Source i > * p> * * @author * @version $ revision: 1.1 $ date: 2003/05/30 03:28:34 $ * / public class validationUtil { Private static final log log = logfactory.getlog (validationutil.class); // ~ methods =============================== ========================================================================================================================================================== / ** * Validates that two fields match. * @Param bean * @param va * @param field * @param errors * @param request * @return boolean * / public static boolean validateTwoFields (Object bean, ValidatorAction va, Field field, ActionErrors errors, HttpServletRequest request) {String value = ValidatorUtil.getValueAsString (bean, field.getProperty ()); String sProperty2 = field.getVarValue ( "secondProperty"); String value2 = ValidatorUtil.getValueAsString (bean, sProperty2); IF (! genericvalidator.isblankornull (value) {try {if (! value.equals (value2)) {Errors.Add (Field.getKey (), Resources.getActionError (Request, Va, Field); Return False;}}}} catch (exception e) {Errors.Add (Field.getKey (), Resources.getActionError (Request, Va, Field); Return false;}} Return True;} } After you create a good test feature, you need to add him to validation-rules.xml Var value; var secondValue; if (field.type == "select-one") {var si = field.selectedIndIndex; value = field.Options [Si] .value; secondValue = secondfield.Options [Si] .value; Else {value = field.value; secondvalue = secondfield.value;} f ((Field.Type == 'text' || field.type == 'textarea' || Field.Type == 'select-one' || Field.Type == 'Radio' || Field.Type == 'Password') && (DatePattern.Length> 0) && (Value.Length> 0) && (SecondValue.Length> 0)) { VAR MONTH = "mm"; var day = "dd"; var yeear = "yyyy"; var orderMonth = datepattern.indexof (month); var orderday = datepattern.indexof (day); var orderryear = datepattern.indexof (Year) Var fromd = new date (); var Todt = new date (); fromdt.setyear (Value.Substr (ORDERYEAR, 4)); FromDt.SETMONTH (Value.Substr (ORDERMONTH, 2) -1); Fromdt.Setdate (Value.Substr (ORDERDAY, 2)); Todt.Sety.Substr (ORDERYEAR, 4)); Todt.SETMOSTH (SECONDVALUE.SUBSTR (ORDERMONTH, 2) -1); Todt.Setdate (SECONDVALUE.SUBSTR (ORDERDAY , 2)); if (Todt IF (Fields.Length> 0) {FOCUSFIELD.FOCUS (); Alert (Fields.Join ('/ n'));} Return bvalid;}]]> javascript> validator> global> form-validation>