I was recently given a requirement to drive the entity attribute validations at runtime rather than at design time, with the following criteria.
- Ability to change fields to required at runtime.
- To be able to define validation message for field at runtime
- Define validations such as field must be numeric, or contain only alphabets (Used Regular expression for this)
- Localization of validation messages
To accomplish this we can use database dictionary views along with custom database tables to store the validations and perform validations at runtime. The data model diagram is shown below. The key thing then is to use database dictionary views along with these database tables to validate attributes of the entity for a pattern (regular expression). The class that contains the method to perform validations is CustomEntityImpl and each entity that one wants to enable for runtime validation must extend this class and call its validateCustomEntity method in its entity method validator.
In the sample application i have enabled a required and pattern constraint as shown in the following screenshots for dummy entity object’s attribute. The application source and sql script can be downloaded from the below mentioned link. Source Code Note: If you want to test the application you must create tables under user “raman”. Edit: To skip validation for existing attribute that has not been modified you can use the following snippet.
1 2 3 4 | Object attribValue=getAttribute(attrName); int attribIndex=getAttributeIndexOf(attrName); Object oldAttribValue=getPostedAttribute(attribIndex); if(attribValue==null || !attribValue.equals(oldAttribValue)){ |
1 2 3 4 | ArrayList<JboException> list=new ArrayList<JboException>(2); if(attribRequired.equalsIgnoreCase("Y")) { .................... |