对表单的验证有两种:语法验证和语义验证。语法有效是指数据必须有正确的格式,如数据只能包含数字,语义有效是指必须符合逻辑,如时间值不能是一个未来的时间。
struts1.2增添了许多新特征如:validwhen验证规则(validator)
一开始Struts是使用formbean的validate()方法进行验证的。有时候则是在Action中进行验证。通过validator框架你可以不需要通过硬编码的方式进行验证,它使你可以在一个XML中配置对表单的验证,这样做可以很灵活的添加修改删除验证,同时可以重复使用验证规则。你可以使用它在客户端进行基于javascript和服务器端的验证,你也可以自定义验证方法。
具体的验证规则如下:
required Checks that a field value is non-null and not an empty string. requiredif Only available for Struts 1.1. This validator allows one field to be specified as required if another field is null, not null, or equal to a specified value. This validator is deprecated, in favor of validwhen, in releases after Struts 1.1. validwhen Designed to replace requiredif, this validator is available in releases after Struts 1.1. This validator relies on a user-specified test expression that can include references to other fields, field values, and logical relationships. minlength Checks that the number of characters in the field value is greater than or equal to a specified minimum. maxlength Checks that the number of characters in the field value is less than or equal to a specified maximum. mask Validates the field value using a regular expression to determine a match. If the value matches the regular expression, the field is valid. byte Checks that the field value is a valid byte value. short Checks that the field value is a valid short integer value. integer Checks that the field value is a valid integer value. long Checks that the field value is a valid long value. float Checks that the field value is a valid floating-point value. double Checks that the field value is a valid double value. date Checks that the field value matches a specified date format pattern (e.g., MM/dd/yyyy). The match can be strict or lenient; "strict" would require May 10, 1963 to be formatted (using the MM/dd/yyyy pattern) as 05/10/1963; "lenient" would allow 5/10/1963. range Checks that the field value is within a specified numeric range. This valdiator has been deprecated in favor of the type-specific range checks (intRange, floatRange, etc.). intRange Checks that the field value is within a range bounded by two int values. floatRange Checks that the field value is within a range bounded by two float values. doubleRange Checks that the field value is within a range bounded by two double values. creditCard Verifies that the format of the field value is valid for a credit card number. This validator is convenient to use instead of using mask. email Verifies that the format of the field value is valid for an electronic mail address (e.g., foo@bar.com). This validator is convenient to use instead of working with mask. url Verifies that the value entered is a valid uniform resource locator. Use this validator when you want to validate an input web location or hyperlink value.
评论