Package com.smartgwt.client.docs.serverds

# Class Validator

java.lang.Object
com.smartgwt.client.docs.serverds.Validator

public class Validator extends Object
A validator describes a check that should be performed on a value the user is trying to save.

This class is not meant to be created and used, it is actually documentation of settings allowed in a DataSource descriptor (.ds.xml file), for use with Smart GWT Pro Edition and above. See `com.smartgwt.client.docs.serverds` for how to use this documentation.

Validators are specified for DataSource fields via the `DataSourceField.validators` property and `are executed in the order in which they are defined`. Validators that need not be run on the server can also be specified for a specific `FormItem` or `ListGridField`.

Smart GWT supports a powerful library of `ValidatorTypes` which have identical behavior on both the client and the server.

Beyond this, custom validators can be defined on the client and custom validation logic added on the server. Note that the `regexp` and `mask` validator types are very flexible and can be used to perform virtually any kind of formatting check that doesn't involve some large external dataset.

Custom validators can be reused on the client by adding them to the global validator list, via the `addValidator()` method.

See Also:
  - `ValidatorType`

- ## Field Summary

  Fields
  Modifier and Type
  Field
  Description
  `AdvancedCriteria`
  `applyWhen`
  Used to create a conditional validator based on criteria.
  `boolean`
  `caseSensitive`
  Applies only to the "isUnique" and "hasRelatedRecord" validators and controls whether the search for existing records is case sensitive or not.
  `Boolean`
  `clientOnly`
  Indicates this validator runs on the client only.
  `StringMethod`
  `condition`
  For a validator that is not a built-in `ValidatorType`, a `Callback`, function, or JavaScript expression to evaluate to see if this validator passes or fails.
  `String[]`
  `dependentFields`
  User-defined list of fields on which this validator depends.
  `String`
  `errorMessage`
  Text to display if the value does not pass this validation check.
  `Boolean`
  `exclusive`
  When set to true, values that equal the specified `min` or `max` values will fail validation.
  `String`
  `expression`
  For validators that use a regular expression or conditional logic, this property specifies the expression to evaluate.
  `AdvancedCriteria`
  `failWhen`
  Defines validation purely via criteria: the record is invalid when the criteria match.
  `Object`
  `max`
  Indicates the maximum value for range-based validators.
  `Object`
  `min`
  Indicates the minimum value for range-based validators.
  `String`
  `operationId`
  Applies only to the "isUnique" validator; allows you to name a specific `operation` for the server-side uniqueness check.
  `String`
  `otherField`
  For validators of type `matchesField`, specifies the name of the other field whose value this field must match.
  `AdvancedCriteria`
  `passWhen`
  Defines validation purely via criteria: the record is valid when the criteria match.
  `Integer`
  `precision`
  For validators of type "floatPrecision", the `precision` attribute specifies the maximum number of decimal places allowed.
  `Boolean`
  `roundToPrecision`
  For validators of type "floatPrecision", when set to true, a value with more decimal places than `precision` will be rounded to the specified precision rather than failing validation.
  `String`
  `serverCondition`
  For validators of type "serverCustom" only: a scriptlet in any supported JSR223 scripting language which is run in order to see if validation passes.
  `ServerObject`
  `serverObject`
  For validators of type "serverCustom" only, a `ServerObject` declaration that allows the Smart GWT Server to find a Java class via a variety of possible approaches, and call a method on it to perform validation.
  `Boolean`
  `serverOnly`
  Indicates this validator runs on the server only.
  `Boolean`
  `stopIfFalse`
  Normally, all validators defined for a field will be run `in the order in which they are defined` even if one of the validators has already failed.
  `Boolean`
  `stopOnError`
  Indicates that if this validator is not passed, the user should not be allowed to exit the field - focus will be forced back into the field until the error is corrected.
  `ValidatorType`
  `type`
  Type of the validator.
  `Boolean`
  `validateOnChange`
  If true, validator will be validated when each item's "change" handler is fired as well as when the entire form is submitted or validated.

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `Validator()`

- ## Method Summary

  ### Methods inherited from class java.lang.Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Field Details

  - ### caseSensitive

    public boolean caseSensitive
    Applies only to the "isUnique" and "hasRelatedRecord" validators and controls whether the search for existing records is case sensitive or not.

    Default value is false

  - ### passWhen

    public AdvancedCriteria passWhen
    Defines validation purely via criteria: the record is valid when the criteria match. If the criteria do not match, the validator fails and returns `errorMessage`.

    This is an alternative to `serverCondition` that uses declarative criteria instead of scripting. No `type` is required — the criteria ARE the validation logic.

    Supports the full ServerDynamicCriteria syntax including references to the current user, operation type, and fields on related DataSources.

    If the outermost criterion omits `fieldName` (and has no `criteria` sub-array), it defaults to the name of the field the validator is declared on. This allows a compact shorthand:

          <!-- equivalent to fieldName="status" -->
          <field name="status">
            <validators>
              <validator errorMessage="Must be Active">
                <passWhen operator="equals" value="Active"/>
              </validator>
            </validators>
          </field>

          <validator errorMessage="Status must be Pending or Active">
            <passWhen fieldName="status" operator="inSet">
              <value>
                <value>Pending</value>
                <value>Active</value>
              </value>
            </passWhen>
          </validator>

    Default value is null

    See Also:
      - `failWhen`
      - `applyWhen`

  - ### errorMessage

    public String errorMessage
    Text to display if the value does not pass this validation check.

    If unspecified, default error messages exist for all built-in validators, and a generic message will be used for a custom validator that is not passed.

    Server-side this string evaluates in a Velocity context where the variables $value and $fieldName are available and refer to the supplied value and the field name, respectively. Note that if the validator is intended to run both on the client and server, you shouldn't use these velocity vars as they will not be expanded on the client and the user may then see raw uninterpolated strings.

    Default value is null

  - ### roundToPrecision

    public Boolean roundToPrecision
    For validators of type "floatPrecision", when set to true, a value with more decimal places than `precision` will be rounded to the specified precision rather than failing validation.

    Default value is null

    See Also:
      - `precision`

  - ### validateOnChange

    public Boolean validateOnChange
    If true, validator will be validated when each item's "change" handler is fired as well as when the entire form is submitted or validated. If false, this validator will not fire on the item's "change" handler.

    Note that this property can also be set at the form/grid or field level; If true at any level and not explicitly false on the validator, the validator will be fired on change - displaying errors and rejecting the change on validation failure.

    Default value is null

  - ### otherField

    public String otherField
    For validators of type `matchesField`, specifies the name of the other field whose value this field must match.

    Default value is null

  - ### dependentFields

    public String[] dependentFields
    User-defined list of fields on which this validator depends. Primarily used for validators of type "custom" but can also be used to supplement `applyWhen` criteria.

    Note that for validators run on the server, fields required due to `dependentFields` but not present in the `DSRequest.data` of an update because they haven't changed will be filled in from the server DataSource.

    Default value is null

    See Also:
      - `applyWhen`

  - ### stopOnError

    public Boolean stopOnError
    Indicates that if this validator is not passed, the user should not be allowed to exit the field - focus will be forced back into the field until the error is corrected.

    This property defaults to `FormItem.stopOnError` if unset.

    Enabling this property also implies `FormItem.validateOnExit` is automatically enabled. If this is a server-based validator, setting this property also implies that `FormItem.synchronousValidation` is forced on.

    Default value is null

  - ### applyWhen

    public AdvancedCriteria applyWhen
    Used to create a conditional validator based on criteria. The criteria defines when the validator applies — evaluated against the current record, `rule\n context`, and (when referencing related DataSources) locally cached data or the server. If the criteria match, the validator is processed; otherwise it is skipped and assumed valid.

    To use an `applyWhen` criteria the form or grid must use a `DataSource`.

    NOTE: `applyWhen` is not supported for "binary" fields.

    ### Server and client use

    Conditional validators are enforced both on the server and on the client-side when defined on a DataSource field as shown in the examples below. Note the `applyWhen` element is treated as a `Criterion`.

          <!-- Conditional requirement: reason is required when
               the order is being cancelled -->
          <field name="reason" type="text">
            <validators>
              <validator type="required">
                <applyWhen fieldName="status" operator="equals"
                           value="Cancelled"/>
              </validator>
            </validators>
          </field>

          <!-- Shipped orders: shipDate must not be before
               orderDate -->
          <field name="shipDate" type="date">
            <validators>
              <validator
                  errorMessage="Ship date cannot be before order date">
                <applyWhen fieldName="status" operator="equals"
                           value="Shipped"/>
                <passWhen fieldName="shipDate"
                          operator="greaterOrEqualField"
                          value="orderDate"/>
              </validator>
            </validators>
          </field>

    The first example shows a conditional `required` validator using `shorthand\n format`. For conditionally required fields, prefer `DataSourceField.requiredWhen` — it is simpler (no validator wrapper), enforced on both client and server, and supports the full ServerDynamicCriteria syntax. Using `applyWhen` with `type:"required"` as shown here still works but introduces complexities around partial-record edits; see the discussion at the end of the `DataSourceField.required` help topic.

    Conditional validators can also be applied to `Component XML` and to DynamicForm or ListGrid fields in Java code as well.

    ### Authentication, request context, and relational references

    Because the type of `applyWhen` is ServerDynamicCriteria, the `fieldName` in criteria can also reference:
    - The current user and request context (`auth.*`, `context.*`) — see ServerDynamicCriteria for which variables are available client-side vs. server-only
    - Fields on related DataSources via `dot notation`, e.g. `Order.status`
    See ServerDynamicCriteria for the full syntax.

    ### Security

    On the server, `applyWhen` criteria are evaluated against the stored database record overlaid with submitted update values. Client-sent `oldValues` are never used, preventing spoofing attacks where a client fabricates field values to bypass validation. For fields not included in the submitted update, the database value is used.

    Default value is null

    See Also:
      - `passWhen`
      - `failWhen`

  - ### serverCondition

    public String serverCondition
    For validators of type "serverCustom" only: a scriptlet in any supported JSR223 scripting language which is run in order to see if validation passes. For example:

              <validator type="serverCustom">
                  <serverCondition language="groovy"><![CDATA[
                      value < dataSources.StockItem.fetchById(record.itemId).quantity
                  ]]></serverCondition>
              </validator>

    The scriptlet should return a boolean true or false value - failing to return a value will be considered a false result (validator failed). If your expression is syntactically invalid, an exception is thrown and the error message is displayed in the client.

    See `ServerScript` for general information on Server Scripting and JSR223, and `VelocitySupport` for general information on Velocity support, and also see below for special rules for Velocity.

    Available variables The following variables are available in a `serverCondition`:

    - dataSource - The current DataSource
    - record - Other submitted values part of the same update
    - value - The value of the field
    - validator - The config of this validator, including all attributes declared on the <validator> tag, presented as a `Map`
    - field - The field (as a `DSField` object)
    Note that "record" will contain only other values submitted at the same time, not the complete DataSource record. For most types of cross-field validation, you should fetch the current saved record using the server-side API DataSource.fetchById(). For example, in Velocity:

              $dataSource.fetchById($record.primaryKeyField).otherFieldName

    Note that, while a DSRequest provides dsRequest.oldValues, these values cannot be relied upon for a security check since they could be faked.

    Server-side custom validators also have access to the standard set of context variables that come from the Servlet API. However, be aware that if you write conditions that depend upon these variables, you preclude your Validator from being used in the widest possible variety of circumstances; for example, in a command-line process. Rather, it will be tied to operating in the context of, say, an `HttpSession`.

    Given the above caveat, the following context variables are also available:

    - servletRequest - The associated `HttpServletRequest`
    - session - The associated `HttpSession`
    - httpParameters - This variable gives you access to the parameters `Map` of the associated `HttpServletRequest`; it is an alternate form of `$servletRequest.getParameter`
    - requestAttributes - This variable gives you access to the attributes `Map` of the associated `HttpServletRequest`; it is an alternate form of `$servletRequest.getAttribute`
    - sessionAttributes - This variable gives you access to the attributes `Map` of the associated `HttpSession`; it is an alternate form of `$session.getAttribute`

    Special considerations for Velocity

    To return a true or false value in Velocity, you script can either be just an expression that returns a boolean value, or the result of evaluating the Velocity template can result in output of "true" or "false". All of the following are valid forms:

    `$value < 100
    $util.contains($value, "some string")
    $record.someField`(assuming that "someField" contains a boolean value)`
    $value > $record.otherField`

    For additional troubleshooting information when Velocity expressions aren't working as expected, set the log category org.apache.Velocity to DEBUG in log4j.isc.config.xml.

    Because it's tricky to call arbitrary Java methods in Velocity, the following special objects are passed to Velocity for convenience:

    - dataSources - The list of all DataSources, accessible by name (so, for example, `$dataSources.supplyItem` refers to the `supplyItem` DataSource object).
    - util - A `com.isomorphic.util.DataTools` object, giving you access to all of that class's useful helper functions

    Note: if your validation logic can be expressed as ServerDynamicCriteria, consider using `passWhen` or `failWhen` instead — these provide automatic client-side enforcement without any scripting.

    Default value is null

  - ### failWhen

    public AdvancedCriteria failWhen
    Defines validation purely via criteria: the record is invalid when the criteria match. If the criteria match, the validator fails and returns `errorMessage`. Inverse of `passWhen`.

    Supports the full ServerDynamicCriteria syntax including references to the current user, operation type, and fields on related DataSources.

    If the outermost criterion omits `fieldName`, it defaults to the field the validator is declared on (same shorthand as `passWhen`).

          <validator errorMessage="Cannot use status 'Cancelled'">
            <failWhen fieldName="status" operator="equals"
                      value="Cancelled"/>
          </validator>

    Default value is null

    See Also:
      - `passWhen`
      - `applyWhen`

  - ### stopIfFalse

    public Boolean stopIfFalse
    Normally, all validators defined for a field will be run `in the order in which they are defined` even if one of the validators has already failed. However, if `stopIfFalse` is set, validation will not proceed beyond this validator if the check fails.

    This is useful to prevent expensive validators from being run unnecessarily, or to allow custom validators that don't need to be robust about handling every conceivable type of value.

    Default value is false

  - ### exclusive

    public Boolean exclusive
    When set to true, values that equal the specified `min` or `max` values will fail validation. When setting this property, consider also adding a `custom message`.

    Default value is null

    See Also:
      - `min`
      - `max`

  - ### expression

    public String expression
    For validators that use a regular expression or conditional logic, this property specifies the expression to evaluate.

    For `regexp` validators, this should be a regular expression (as a string or RegExp object) that the value must match.

    For `requiredIf` validators, this should be a `stringMethod` that returns `true` if the field should be required. The function receives four parameters: `item` (the form item), `validator` (the validator object), `value` (the field value), and `record` (the form values).

    Default value is null

  - ### type

    public ValidatorType type
    Type of the validator.

    This can be one of the built-in `ValidatorType`, the string "custom" to define a custom validator, or the string "serverCustom" to define a server-only custom validator.

    Default value is null

  - ### serverOnly

    public Boolean serverOnly
    Indicates this validator runs on the server only.

    Default value is null

  - ### clientOnly

    public Boolean clientOnly
    Indicates this validator runs on the client only.

    Normally, if the server is trying to run validators and finds a validator that it can't execute, for safety reasons validation is considered to have failed. Use this flag to explicitly mark a validator that only needs to run on the client.

    Default value is false

  - ### condition

    public StringMethod condition
    For a validator that is not a built-in `ValidatorType`, a `Callback`, function, or JavaScript expression to evaluate to see if this validator passes or fails.

    Because the validator declaration itself is passed as a parameter to `condition()`, you can effectively parameterize the validator. For example, to create a validator that checks that the value is after a certain date:

              { type:"custom", afterDate:new Date(),
                condition:"value.getTime() > validator.afterDate.getTime()" }

    Reusable validators, like the above, can be registered as a standard validatorType by calling `addValidator()`.

    Note that, if a field is declared with a builtin `FieldType`, the value passed in will already have been converted to the specified type, if possible.

    For the required parameters, see the documentation for ValidatorConditionCallback.

    Default value is null

  - ### min

    public Object min
    Indicates the minimum value for range-based validators. By default, range-validators are inclusive, meaning that values that equal the `min` value will pass validation. To make a validator-range exclusive, and have equal values fail validation, set `validator.exclusive` to true and provide a `custom message`.

    Default value is null

    See Also:
      - `max`
      - `exclusive`

  - ### serverObject

    public ServerObject serverObject
    For validators of type "serverCustom" only, a `ServerObject` declaration that allows the Smart GWT Server to find a Java class via a variety of possible approaches, and call a method on it to perform validation.

    The target object must implement a method whose first 4 arguments are: `Object value, Validator validator, String fieldName, Map record`

    (`com.isomorphic.datasource.Validator` is a subclass of `Map` that represents a validator's configuration, and also provides APIs for implementing templated error messages).

    You provide the name of the method to call by specifying `methodName` as part of the serverObject declaration. If you do not specify a methodName, Smart GWT expects to find a compliant method called "condition".

    Additional arguments may be declared and are automatically supplied based on the declared argument type, via `DMI`. Available objects include:

    - DataSource - the DataSource where this validator is declared, an instance of com.isomorphic.datasource.DataSource or a subclass
    - HttpServletRequest - from standard Java servlets API
    - HttpServletResponse - from standard Java servlets API
    - ServletContext - from standard Java servlets API
    - HttpSession - from standard Java servlets API
    - RequestContext - an instance of com.isomorphic.servlet.RequestContext
    - RPCManager - the RPCManager associated with the transaction this validation is part of; an instance of com.isomorphic.rpc.RPCManager
    - DSRequest - the DSRequest this validation is part of; an instance of com.isomorphic.datasource.DSRequest
    - DSField - the datasource field which value is validated; an instance of com.isomorphic.datasource.DSField
    - ValidationContext - the context where value is validated; an instance of com.isomorphic.datasource.ValidationContext
    Note that any servlet-related objects will not be available if your validator is run outside of the scope of an HTTP servlet request, such as a command-line process.

    Note that "record" will contain only other values submitted at the same time, not the complete DataSource record. For most types of cross-field validation, you should fetch the current saved record. For example:

              final Map<String, Object> existingRecord = dataSource.fetchById(record);

    Note: if your validation logic can be expressed as criteria, consider using `passWhen` or `failWhen` instead of a DMI call — these provide automatic client-side enforcement. Even if only part of your logic can be expressed as criteria, using `applyWhen` to gate a `serverCustom` validator avoids the server call when the condition doesn't apply.

    Default value is null

  - ### operationId

    public String operationId
    Applies only to the "isUnique" validator; allows you to name a specific `operation` for the server-side uniqueness check. Ignored on the client.

    Default value is null

  - ### max

    public Object max
    Indicates the maximum value for range-based validators. By default, range-validators are inclusive, meaning that values that equal the `max` value will pass validation. To make a validator-range exclusive, and have equal values fail validation, set `validator.exclusive` to true and provide a `custom message`.

    Default value is null

    See Also:
      - `min`
      - `exclusive`

  - ### precision

    public Integer precision
    For validators of type "floatPrecision", the `precision` attribute specifies the maximum number of decimal places allowed. If the value has more decimal places than specified and `roundToPrecision` is set, the value will be rounded to the specified precision and validation will pass; otherwise validation fails.

    Default value is null

    See Also:
      - `ValidatorType`

- ## Constructor Details

  - ### Validator

    public Validator()