Input validation allows data services to validate the input parameter values that are presented in a request. This allows to stops the execution of the request, if the input has not met the required criteria. WSO2 Data Services Server provides a set of built-in validators which will be sufficient for the mostly used use cases. And also it provides an extension mechanism, where custom validators can be written.
So input validators in WSO2 DSS can be categorized as follows.
- Built-in validators
- Long Range Validator- Validates if an integer value is in the specified range.
- Double Range Validator- Validates if an integer value is in the specified range.
- Length Validator- Validates the string length of a given parameter against a specified length.
- Pattern Validator- Validates the string value of the parameter against a given regular expression.
- Custom Validator- allows the user to instroduce custom validation logic by adding Custom Validators.
In this post custom validators will be discussed in detail.
For defining a custom validator, the user must implement the interface "org.wso2.carbon.dataservices.core.validation.Validator" or the "org.wso2.carbon.dataservices.core.validation.ValidatorExt". If the validation fails, the validate method in the interface by default throws an exception of type
The definition of the Validator interface is as follows.
ValidatorExt interface is introduced from the DSS 3.5.1 release onwards. If the custom validator needs to be initialized by providing any properties, it is required to implement the interface ValidatorExt. It extends the Validator interface and the definition of the interface is as follows.
A sample Java code for Custom Validator class which implements the ValdiatorExt is as follows. You can add any validation logic as required.
The class structure for the above class is as follows.
You can complie and create the jar file as follows. When doing the compile, you need to point your build path to org.wso2.carbon.dataservices.core_x.x.x.jar file.
Then copy the created jar file to the wso2dss-x.y.z/repository/components/lib folder and restart the service. Then you can create the data service which use this custom validator.
When adding the validator you can add the custom properties via the UI as follows.
The complete data services definition for the above example is as follows.
Now service creation is completed and you can test. For example if you invoke the AddEmployee operation with invalid email length you will receive a response like below.