Struts Validator Verifier Usage Guide

xiaoxiao2021-03-06  39

Struts Validator Validator Guide (based on Struts Validator Guide) Author: David Winterfeldt David James Turner James Rob Leland Robert translation: Hou Si super validator: from 0.5 version, the validator in some form in has been achieved, he was first included in the development In the packet, the core code moved to the Jakarta Commons package and the Struts special extension as part of Struts 1.1. Many developers have always used the Struts validator, which first outlines the core functionality of the validator, and then introduces the changes and new features in Struts1.1. If you configure the validator plugin, you should extend the ValidatorForm instead of Actionform so that it can load your Validator resource. According to the name attribute of the Action in the struts-config.xml file, he is the corresponding verifier corresponding to the current Form, so the name property of the FORM element in Validator-Rules.xml should match the name attribute value of the Action. Another option is to extend the ValidatorActionform instead of validatorform, ValidatorActionForm uses the path property of the action in struts-config.xml, so the value of the Path property should be matched to the FORM of the value in Validator-Rules.xml. A separated action can define each page of multi-page FORM, and the verification rule can be associated with an action rather than the page number, just like the multi-page Form example in the verification example. Internationalization in the Validator-Rules.xml file can organize Formset. Formset has the properties corresponding to the Java.util.Locale class: such as language, country, and variable properties, if they are not defined, the Formset will set it to the default value. A Formset can also have associated constants. You can also define global Global elements with Formset at the same level, and he also has a constant as Formset. Note: You must declare a default formset without an internationalization before the Internationalized Formset. This can have a default version if Validator does not find local. The default error message value of the plug-in verifier can be overwritten by the MSG element. So the alternative method for generating error messages for the Mask verifier is to use the MSG property, if the field's Name property matches the Name property of the validator, the MSG property of the field will use the field. Error Messages can set parameters such as Arg0-Arg3. If no Arg0-Arg3's Name property is set, Error Messages will use them as the default build parameter value. If the Name property is set, you can specify the parameter to a specific pluggable verifier, and then these parameters will be used when constructing an error message.

< Var-name> mask ^ [A-ZA-Z] * $ The default arg0-arg3 element will be in message resources Find the corresponding key if the resource property is set to false, she will pass the value directly, not to find from the message resource. Note that in the version 1.1, you must explicitly define the message resources used in the verification in each module, otherwise the top-level resource will be used. min 10 < / var> max 20 constant / variable global constant You can define in the global tag, and FormSet / local constants can be created in the FormSet tag. The constant is only only the Property property of the field, the Value property of the field's VAR element, the key property of the field's MSG element, the KEY property of the arg0-arg3 element of the field. The variables of the fields can also be replaced in Arg0-Arg3 elements (for example, $ {var: min})). The order of replacement is the first, and the global constant constant is second, and the Arg Elements variable is last. zip ^ / d {5} (- / d {4})? $ < / Global>

mask $ { ZIP} The verifier can store variables under the field below, and these variables get through the field GetVar ((String Key) method. min 10 max 20 Using Validwhen Design Complex Verification Using ValidWhen to design complex verification A frequent requirement is to verify another field according to a field (for example, if you want users to enter the password to confirm the value password), the other is that only one field in the form is only a certain field with a certain value is required. Enter. The new Validwhen verification rule will soon be included in the 1.1 Struts version, she is used to handle this situation. ValidWhen rules handle a single variable field, called test. This variable is a Boolean Expressions, if valid is valid, it must be true. You can include this variable with: U single quotes or dual quotation marks Literals, u decimal, hexadecimal, octal Integer Literals, u Null and NULL and Empty string matching, u Other FORM fields that can be referenced by attribute names, such as Customerage, u can be used outside the outside Segment, for example, ChildLastName [2], u can default Implicit due to index fields, such as ChildlastName [], she will use the same index as an indexed field, and the literal * refers to it contains the value of the current test field. ,

As an example, a FORM containing the communication address and the mailbox field is considered. If the communication address is not empty, the mailbox field is a must-have required. You can define the ValidWhen rules: test (SendNewsletter == Null) or (* this *! = null) The above definition means: If the communication address is empty or not Valid when the field is in the field. Here has a slightly complex example, which uses the index field. Assume that there is a form that allows the user to enter the part number and quantity they want to order. An array of class ORDERLINE beans is used to hold input items called ORDERLINES. If You Wished to Verify That Every Line with Part Number Also Had a Quantity Entered, You Could Do IT with: If you want to have quantities in the check order, you can do this: test ((ORDERLINES []. partnumber = = NULL) OR (* this *! = null) Here is: if the corresponding partnumber field is empty, or this field is not empty, then Field is effective. The last example, imagine a form, the user must enter their height of inches all, if they are at a height of 60 inches, there is an error. (It is an error to have, checked off nbapointguard as a carence.) test ((HeightinInches> = 60) or (* this * == null)

To make a brief description of the program: All comparison must be encapsulated in the Parens. All Comparsons Must Be Enclosed in Parens. You can link and or or or or later. If the two items of comparison can be converted to an integer, use the NuMERIC comparison, otherwise the string is compared. Plugable verifier verification is loaded from the validation.xml file, the default authentication rule defines in the Validation.xml file, defaults Required, Mask, Byte, Short, Int, Long, Float, Double, Date (no local) Support), And a nameic range. "Mask" mode depends on the default value installation requirements, which means "required" can be done, "'Mask" will run the previous "Required" and "Mask" methods to be included in the frame. Any field is not "Required" and is empty or zero length will skip other verification. If you use the JavaScript tag, client JavaScript looks for values ​​in the Validator's JavaScript property and generates an object that verifies the FORM method. To get more detailed explanations about the Detail of JavaScript Validator Tags, see the HTML tag API reference. "'mask'" means you use a regular expression mask to verify fields, which use Jakarta's regular expression pack, all valid rules store in the Validator-Rules.xml file, the main class used by Org.apache. Regexp.re. validation.xml authentication configuration file Example:

Defining the parameters of the plug-in verifier method are some class lists separated by commas, and the method properties need to have a signature that meets the above list. The list is combined by the following: java.lang.object - the bean to verify. Org.apache.commons.validator.validatorAction - Current ValidatorAction. Org.apache.commons.validator.field - the field to verify org.apache.struts.Action.ActionerRORS - If the validation error will join the analog object javax.servlet.http.httpservletRequest - the current REQUEST object. Javax.servlet.ServletContext - Application ServletContext. Org.apache.commons.validator.validator - Current Org.Apache.commons.validator.validator instance. Java.util.locale - the current user's Locale. Multi-page Form field section has an optional page property, which can be set to an integer, all validations of the page are less than or equal to the current page of the server-side authentication, all the fields of the field less than or equal to all fields on the client page Verify the current page of the current page verification less than or equal to the server-side verification. A MUTLI-Part form requires defining page properties:

IF (! genericvalidator.isblankornull (value) {try {if (! value.equals (value2)) {Errors.Add (Field.GetKey (), Resources.getActionError (Application, Request, Va, Field); Return False }}} catch (Exception E) {Errors.Add (Field.getKey (), Resources.getActionError (Application, Request, Va, Field); Return False;}}} Known Bug Struts Validator depends on Commons Validator Package Therefore, problems reporting and enhanced demand may be listed in two products. · Struts Validator Bugzilla Reports · Commons Validator Bugzilla Reports Change and DepRecations New Tag Properties. tag has a new attribute definition. Use DTD validation in commons-validator.jar.

The currently used verification XML file is DTD according to Commons-Validator.jar. Struts is not at Validator-Rules.xml and Validator.xml. Separate a separate DTD separately, and Commons-Validator now maintains a unified validator.dtd. Modify all Validator.xml files DTD references to Space field.

The current default ignores blank fields in all base verification types, if you ask a field to be entered, add "Required" in the Depends property defined by the Validator.xml file of your application. New range RANGE method.

The Intrange & FloatRange method has been added in JavaScript and Java. Conditionally Required field.

The biggest modification is the ability to add conditionally Require authentication based on the value of its field. It allows you to define logices such as "Only the x field is not empty" Y field is 'Male' is valid ", this is a recommended method for implementing the above logic, this method will be implemented in the first version of the 1.1 version. The RequireDIF verification rule added in version 1.1 will be removed in the new version. However, if you are preparing to use Requiredif, there is a short tutorial. Let us assume that you have a medical information form with 3 fields, gender SEX, pregnancy test pregnancytest, test results test, if gender is 'f' or 'f', pregnancy test pregnancytest is Required, if pregnancytest is not empty, Test results TestResult are Required.

The input item for your validation.xml file should be like this:

Field [0] sex FieldTest [0] Equal FieldValue [0] f Field [1] sex fieldtest [1] Equal FieldValue [1] f Fieldjoin or Field [0] pregnancytest FieldTest [0] notnull

Here is a more complex example with an index, if your struts-config.xml has this: Here DependentListForm Bean has four properties of LastName, FirstName, Dob, CoverageType, you can define a verification rule: Field [0] Lastname FieldIndexed [0] True -name> FieldTest [0] notnull field [0] LAS TName FieldIndexed [0] true Fieldtest [0] notnull

field [0] < VAR-VALUE> Lastname FieldIndexed [0] true < Var> Fieldtest [0] notnull field [1] insuredependents FieldTest [1] equal FieldValue [1] true Fieldjoin and The meaning here is: if the lastname field is non-empty, the firstname field Required. Because the field indexed is true, this means that the lastname of indexed must be the same as the firstname index, the DOB is the same, unless Date is not empty. If the last value is not empty when the LastName is indexed, and the Non-index field insureependeents is true, CoveRageType is Only Require. You can use any numbers in [n] in [n], the only limit is that they must be And or OR, you can't mix. DepRecation:

u JavaScript and Java Range methods. U StrutsvaliDator & StrutsvaliDatorUtil class DepRecation Method API Guide A Concise Struts Verifier API Guide can help you start. Verifier Resources Struts Validator: Validating Two Fields Match author matt rail. (Two field matching verification) About the method of using the method. (Sample section is translated herein) DynaForms and the validator author James Turner and Kevin Bedell. Struts Kickstart's chapter (Dynamic Form and Valid), freely download PDF). Validating User INPUT author David Winterfeldt and Ted Husted. One of the chapters of Struts In Action, free download (PDF). Method of Use: Ugly && Snowtears: After two weeks of unremitting efforts, read a lot of information, and finally on Validator had a preliminary understanding, order a bit, shallow talked about writing, I hope to have some help, There is definitely there are many ways to say that they are not accurate, please advise real_herozx@163.net

Wang Yi: According to the above two articles, it is configured to configure RUTS-Config.xml: 1, add the ApplicationResources configuration file. Such as: < Message-resources parameter = "com.dc.sibss.com.struts.applicationresources" />] Part of com.sibss.com.struts.ApplicationResources is the path to the resource file, the role of this file is non-programming for error messages Customization and multilingual support. If we use the Chinese platform operating system, the ApplicationResource_zh_cn.properties file will be first look for by default, and then ApplicationResources_zh.properties, if the first two files are not found, the ApplicationResources.properties file will be found. Ability to display error prompts on the page, we also need to add the following to the end of the ApplicationResources.properties file: errors.required = {0} is required. Errors.minLength = {0} cannot Be Less Than {1} characters. Errors.maxlength = {0} cannot berough Than {2} characterid = {0} is invalid. Errors.byte = {0} Must be an byte. errors.short = {0} Must be an Short. ERRORS.INTEGER = {0} Must be an integer. Errors.long = {0} Must be an long. errors.double = {0} Must be an double. Errors. Date = {0} is not a date. errors.range = {0} is not in the range {1} through {2}. Errors.creditcard = {0} is not a valid Credit C Ard Number. Errors.email = {0} is an invalid e-mail address. The above is only the error type of erruts now supported, if you customize new types of error verification, you need to add it. Your own content. The {0} in the above is referring to the parameters submitted by the error. For example: When you need the "user name" on the page, you can't empty (that is, the ErrorS.Required), this {0} represents "User Name", so if you don't fill in the username, you will throw the following error: User IS Required. (You can modify Chinese as needed)

We may have noticed that since the error prompt information needs to be configured, how is the "User Name" system in the above example? That's right! Also modify this configuration file, the content is as follows: Visitcust.Rror.Name.Required =
User name This time When "User Name" is empty, the Struts background program defines the unreasonable or more. In addition, the above "VisitCust.Name.Required" is specified when Validation.xml configures authentication content. See the following description. Note: In general, your system only needs an ApplicationResources file, so members of the development group do not add their own resource files. You only need to use multiple ApplicationResources files when your project group is developed, but your Struts-config.xml file will have the same number. 2, add the Validator plugin in the struts-config.xml file: After adding this plugin, your application has the environment where Validator is used, such as:

If you want to use multiple ***. XML files, the Value part is written as the value = "/ Web-inf / validator-rules.xml, / web-inf / value.xml, / web -INF / VALIDATION1.XML, /WEB-INF /VALIDATION2.XML "In , it is necessary to add validate =" true "to use validate =" True "in . Verify configuration on the client: Write

The basic authentication can be made in the validation.xml file. This method is to verify at the client, and the client can see the entire code of the JavaScript section. Security is not high 2, ValidatorForm validate method. 1, validate () method: to make their ActionForm inheritance ValidatorForm class, write their own methods in which: public ActionErrors validate (ActionMapping mapping, HttpServletRequest request) {ActionErrors errors = new ActionErrors () ;. . . . . . IF (MyText.Equals ("AAA")) {// my example. ("MyText", New ActionError ("MyText.Error");}. . . . . . Return Errors;

} At this time, if this method is written, it will block the verification section defined in validation.xml. In other words, the system is running, and the defined error verification part of this ActionForm in Validation.xml does not implement, if not If you write this method, the system runs in Validation.xml in Validation.xml to operate the error verification section of this ActionForm. Such methods are verified on the server side and verify that some code clients are not visible. 2. Create your ActionForm and let it inherit the org.apache.struts.valiDator.validatorform class. Create your Action implementation and associate with the ActionForm defined above. It should be noted here that it must be set to True when defining this action, and does not implement its validate method in your defined actionform - this means you will use the ValidatorForm's validate method, so you can guarantee you Error verification is normal. Configure the validation.xml file. The basic content is as follows: Requires the verification page Name Check content > Al =" $ {var: maxlength} "name =" max "/> determines the longest limit length maxlength maxlength 20 Note: The arg0 and arg1 here represent the parameters enclosed using "{}" in the ApplicationResources file. For example: errors.range = {0} is not in the range {1} through {2}.

Three parameters are defined, so you also need to define , , to display the error message.

Errors.maxlength = {0} cannot Be Greater Than {2} character, defined 0, 2 parameters, so you need to define and two parameters.

maxlength 80 < / Field> Add as follows before the of the verification page: 3, DYN Avalidatorform does not need to write the corresponding ActionForm, just configure your ActionForm in struts-config.xml:

"java.lang.string" /> Set the corresponding item in Form-property, such as MyText, MytexTarea, how often, when executed, then write the ActionForm in Validation.xml The hopeful verification code is OK. There is no need to write anything in the JSP file, and the verification is also available on the server, and the verification part code is not visible in JSP. 4. Combination verification If you use dynamic verification DynavalidatorForm, you must write your own corresponding ActionForm, and the corresponding special verification will be considered a considerable limit. At this time, you need to write a special verification part to the corresponding action, if (MyText.Equals ("AAA")) {// my example anctions (); errors.add ("***", New ActionError ("***. Error"); SaveerRors (Request, Errors); Return ("false"));} can be specially verified.

In fact, your FORM can also inherit ValidatorActionform and DynavalidatorActionform, which is the only difference between the ValidatorForm and DynavalidatorForm that they correspond to their corresponding FORM class: When the corresponding FORM class is found in Struts-Config.xml, the former is based on Action The PATH value, while the latter uses the Name value. Example: Struts Verifier: Verify that two fields match

In the guide, there is a section that tells how to create a validator to verify that two fields match, I use this server-side validator (as shown in the example), determine the password verification. This is already working properly; but I also want to try it with the client's JavaScript verification. I wrote my own programs to compare two fields, but they and recommend it to your different (from Validator-Rules.xml). So yesterday, I added how to add JavaScript methods to Validator-Rules.xml. The whole process is configured here (most of the guide already included, saving JavaScript).

How to add a verifier of two fields

Step 1: Generate a class that contains the ValidateTwofields method. In my code, my class is defined as ValidationUTIL, he has the following methods:

Public Static Boolean ValidateTwofield (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;} Step 2: Edit Validator-Rules.xml, join the "Twofields" rule.

SecondValue = secondfield.value;} if (value! = secondValue) {if (i == 0) {FOCUSFIELD = Field;} Fields [i ] = otwofields [x] [1]; bvalid = false;}}}} Fields.Length> 0) {FOCUSFIELD.FOCUS (); Alert (Fields.join ('/ n'));} Return Bvalid;}]> Step 3: in Validation.xml Configure verification for your form: secondproperty confirmpassword Err The field '{0}' of the ors.twofields must be the same as the value of the field '{1}'. An optional work of the third step is to generate validation.xml when an optional work is used. Requires (1) Configure XDoclet (Of course) and (2) Add some @struts tag setpassword method to your form.

转载请注明原文地址:https://www.9cbs.com/read-66221.html

New Post(0)