Struts Validator Verifier Usage Guide Select Blog from Ghostsun

xiaoxiao2021-03-06  26

Struts Validator Verifier Usage Guide

(According to Struts Validator Guide)

Author:

David Winterfeldt David

James Turner James

Rob Leland Robert

translation:

Hou Si Super

Verifier:

From version 0.5, the validator has been implemented in some form, which was originally included in the developer package, and later 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.

globalization

The verification rule in the validator-rules.xml file can be organized to 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.

Property = "Lastname"

Depends = "Required, Mask">

Name = "mask"

Key = "registrationform.lastname.maskmsg" />

Mask

^ [A-ZA-Z] * $

The default arg0-arg3 element will find the corresponding Key in the message resource, if the resource property is set to false, she will pass the value directly, not to find 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.

Property = "integer"

Depends = "Required, INTEGER, INTRANGE">

Name = "Range"

Key = "$ {var: min}"

Resource = "false" />

Name = "Range"

Key = "$ {var: max}"

Resource = "false" />

min

10

max

20

Constant / variable

The global constant can be defined in the global tag, and FormSet / local constant 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 overall constant constant is second,

The Arg Elements variable is final.

zip

^ / d {5} (- / d {4})? $

Property = "ZIP"

Depends = "Required, Mask">

Mask

$ {zip}

The validator can store the variable using the variable portion below the field, which acquires through the field of GetVar ((String Key) method.

Property = "integer"

Depends = "Required, INTEGER, INTRANGE">

Name = "Range"

Key = "$ {var: min}" resource = "false" />

Name = "Range"

Key = "$ {var: max}" resource = "false" />

min

10

max

20

Using Validwhen Design Complex Verification

A frequent requirement using Validwhen is designed to design complex verification is based on a field to verify another field (for example, if you want users to enter the password to confirm the value password), the other is that there is only one field in the form. It is necessary to enter when it is determined. 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. The value of this variable is a Boolean expression, and if it is valid, it must be true. It can contain this expression of this variable:

u single quotes or double quotes string Literals,

U decimal, hexadecimal, octal Integer Literals,

u Null matches NULL and empty strings,

u Other FORM fields that can be referenced by attribute names, such as Customerage,

U can be used outside the index field, such as ChildlastName [2],

u You can default Implicit because of the index field, such as ChildlastName [], she will use the same index to array as the indexed field,

The Litral * Here it refers to 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 like this:

test

(SendNewsletter == Null) or (* this *! = null)

The above definition is that if the communication address is empty or not, this field is valid.

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 names: you could do it with:

If you want to have quantity in the check order, you can do this:

Property = "quantity"

IndexedListProperty = "ORDERLINES"

Depends = "Validwhen">

test

((ORDERLINES []. partnumber == null) or (* this *! = null)

Here is that this field is effective if the corresponding partnumber field is empty, or this field is not empty.

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 Career.)

test

((HeightinInches> = 60) or (* this * == null)

Brief description of the programmer:

All comparison must be packaged in the Parens. All comparisons must be enclosed in parens.

Only two ITMEs can be linked and or or later.

If the two items of comparison can be converted to an integer, use the NuMERIC comparison, otherwise the string is compared.

Insertable verifier

Verification is loaded from the Validation.xml file, the default authentication rule defines in the validation.xml file, default Required, Mask, Byte, Short, Int, Long, Float, Double, Date (no local support), And a Numeric 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. Verifer Configuration Example in the Validation.xml file:

ClassName = "org.apache.struts.validator.fieldchecks"

Method = "ValidateRequired"

Methodparams = "java.lang.object,

Org.apache.commons.valiDator.validatorAction,

Org.apache.commons.validator.field,

Org.apache.struts.Action.Actionerro,

Javax.Servlet.http.httpservletRequest "

Msg = "ErrorS.Required">

ClassName = "org.apache.struts.validator.fieldchecks"

Method = "validatemask"

Methodparams = "java.lang.object,

Org.apache.commons.valiDator.validatorAction,

Org.apache.commons.validator.field,

Org.apache.struts.Action.Actionerro,

Javax.Servlet.http.httpservletRequest "

Msg = "Errors.invalid">

Define can be inserted into verifier

The parameter of the method is a list of some class names separated by a comma, and the method attribute needs 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 - To verify the field

Org.apache.struts.Action.Actionerrors - If the verification error will join an error 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

The field section has an optional page property that 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 validations of the fields are less than or equal to all fields on the client page. Or the current page verified by the server-side verification current page. A MUTLI-Part form requires a page property:

Compare two fields

This is an example of how you can compare whether the two fields have the same value. For example, "users change their password" generally have a password field and a confirmation field.

ClassName = "com.mysite.strutsvalidator"

Method = "ValidateTwofields"

Msg = "errors.twofields" />

SecondProperty

Password2

Public Static Boolean ValidateTwofields

Object Bean, ValidatorAction VA,

Field Field, ActionerRors Errors, HttpServletRequest Request,

ServletContext Application) {

String value = validatorutils.getValueAsstring (bean, field.getproperty ());

String Sproperty2 = Field.getvarvalue ("SECONDPROPERTY");

String value2 = validatorutils.getValueAsstring (bean, sproperty2);

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 relies on the Commons Validator package, so problem reports and enhancements 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 DTD references for all validator.xml files

"- // Apache Software Foundation // DTD Commons Validator Rules Configuration 1.0 // En" "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">

Empty 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]

notnun

Here is a more complex example with the indexed attribute if your struts-config.xml has this:

Type = "org.apache.struts.Webapp.Validator.Forms.validatorform">

Name = "dependents"

TYPE = "org.apache.struts.Webapp.validator.dependnt []" size = "10" />

Here DependentListForm Bean has four properties of LastName, Firstname, Dob, CoverageType, you can define a verification rule:

Property = "firstname" indexedlistproperty = "dependents" depends = "requiredif">

Field [0]

LastName

FieldIndexed [0]

True

FieldTest [0]

notnun

Property = "DOB" indexedlistproperty = "dependents" depends = "requiredif, date">

Field [0]

LastName

FieldIndexed [0]

True

FieldTest [0]

notnun

Property = "CoverageType" indexedlistproperty = "dependents" depends = "requiredif">

Field [0]

LastName

FieldIndexed [0]

True

FieldTest [0]

notnun

Field [1]

InsureDependents

FieldTest [1]

Equal

FieldValue [1]

True

Fieldjoin

and

Here is:

If the lastname field is non-empty, the firstname field require. 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

Verifier 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 part is translated herein)

DynaForms and the Validator author James Turner and Kevin Bedell. Struts Kickstart's chapter (Dynamic Forms and Validers), can freely download PDFs).

Validating User INPUT author David Winterfeldt and Ted HUSTED. One of the chapters of Struts In Action, free download (PDF).

Instructions

Author:

Ugly && Snowtears: After 2 weeks of unremitting efforts, read a lot of information, finally has a preliminary understanding of Validator, sorted up, talking about talking about writing, hoping to have certain help, there must be many I don't have to be inaccurate, please advise Real_herozx@163.net

Wang Yi:

According to the above two articles

Configure RUTS-Config.xml:

1. Add the ApplicationResources configuration file.

Such as:

The part of the com.sibss.com.struts.ApplicationResources is the path to the resource file. The role of this file is non-programming and multilingual support for error messages. If we use the Chinese platform operating system, the default will First find the ApplicationResource_zh_cn.properties file, then ApplicationResources_zh.properties, if the first two files are not found, the ApplicationResources.properties file will be found.

In order to display the error prompt information 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} character.

Errors.INVALID = {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.FLOAT = {0} Must be an float.

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 Card Number.

Errors.Email = {0} is an invalid e-mail address.

The above is just the error type of error type, which is now supported, if you customize new types of error verification, you also need to add 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 name 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 =
Username

This is when the "user name" is empty, the Struts background program defines the unreasonable information 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:

Here, if you want to use multiple ***. XML files, the value of the Value is similar to value = "/ Web-inf / validator-rules.xml, / web-inf / validation.xml, /web-inf/validation1.xml , /Web-inf/Validation2.xml "

In , you should add Validate = "true" when defining the action that needs to be verified.

Four methods of use

1, use JavaScript to verify on the client

Configuration: Write in the JSP file that needs to be verified

>

The XXX here is the forward name, validatexxxx (this) to verify, and XXXX is an Actionform name that you need to verify.

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. Is not high in security

2, ValidatorForm's Validate method

1. Validate () Method: Make your ActionForm inherit the ValidatorForm class, write your own method inside:

Public ActionerRors Validate (ActionMapping Mapping, httpservletRequest Request) {

ActionerroS Errors = new actionerrors ();

. . . . . .

IF (MyText.Equals ("AAA")) {

// my ExampleErRors.Add ("MyText", New Actionerror ("MyText.Error");

}

. . . . . .

Return Errors;

}

At this time, if this method is written, it will shield the verification section defined in validation.xml. In other words, the system is running, and the defined error verification part of this ActionForm is not implemented in Validation.xml, if not written If this method, the system is running in validation.xml to correspond to the operation of the defined 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 name of FORM on the page

Depends = "Required, Maxlength"> Check content

ApplicationResource file correspondence

Determine the length of the longest limit

maxices> Maxlength

20

Note: The Arg0 and Arg1 here represent parameters enclosed in the ApplicationResources file. such as:

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} Characters.

Define 0, 2 parameters, so you need to define and two parameters.

Depends = "Required, Maxlength">

maxices

80

Depends = "Required">

Add the following before the of the verification page:

3, DynavalidatorForm

No need to write the corresponding ActionForm, just configure your ActionForm in struts-config.xml:

Set the corresponding items in Form-property, such as MyText, MyTextArea, how often, when executed, then generate an actionform, and then write the desired verification code in validation.xml, it 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 don't write your own corresponding ActionForm, and the appropriate special verification is subject to a considerable limit. At this time, you need to write a special verification section to the corresponding action.

IF (MyText.equals ("AAA")) {// my example

ActionerroS Errors = new actionerrors ();

Errors.Add ("***", new actionerror ("***. error");

SaveerRors (Request, Errors);

Mapping.Findforward ("false"));

}

It 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 ValidateTwofields

Object bean,

ValidatorAction VA,

Field Field,

ActionerRors Errors,

HttpservletRequest request) {

String value = 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.

Method = "ValidateTwofields"

Methodparams = "java.lang.object,

Org.apache.commons.valiDator.validatorAction,

Org.apache.commons.validator.field,

Org.apache.struts.Action.Actionerro,

Javax.servlet.http.httpservletRequest "Depends =" Required "MSG =" Errors.twofields ">

Function ValidateTwofield (Form) {

Var bvalid = true;

Var Focusfield = NULL;

VAR i = 0;

Var fields = new arrival ();

OTWOFIELDS = New Twofields ();

For (x in otwofields) {

Var Field = form [otwofields [x] [0]];

VAR SecondField = form [otwofields [x] [2] ("SECONDPROPERTY")];

IF (Field.Type == 'Text' ||

Field.Type == 'Textarea' ||

Field.Type == 'Select-one' ||

Field.Type == 'Radio' ||

Field.Type == 'password') {

VAR value;

VAR SecondValue;

// Get Field's Value

IF (Field.Type == "Select-One") {

Var si = field.selectedIndIndex;

Value = Field.Options [Si] .value;

Secondfield.Options [Si] .value;

} else {

Value = Field.Value;

Secondfield.Value;

}

IF (value! = secondValue) {

IF (i == 0) {

Focusfield = field;

}

Fields [i ] = OTWOFIELDS [X] [1];

BVALID = false;

}

}

}

IF (Fields.Length> 0) {

Focusfield.focus ();

Alert (Fields.Join ('/ n'));

}

Return BVALID;

}]>

Step 3: Configure verification for your form in Validation.xml:

SecondProperty

confirmpassword

The field '{0}' of ERRORS.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.

/ **

* Returns the password.

* @Return String

*

* @ Struts.validator type = "required" msgkey = "errors.required"

* @ Struts.validator type = "twofields" msgkey = "errors.twofields"

* @ Struts.validator-args arg1resource = "userform.password"

* @ Struts.validator-args arg1resource = "userform.confirmpassword"

* @ Struts.validator-var name = "secondproperty" value = "confirmpassword"

* /

Public string setpassword () {

Return Password;

}

I have already sent this to the Struts-dev mailing list yesterday, but I have not received any messages.

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

New Post(0)