Data Validation (UI)
In a web application, front-end data validation can reduce the loading on the server. AlchemyJ provides a JavaScript library that validates UI fields using the Data Dictionary configuration defined in your model. This keeps validation logic consistent as the same validation logic can be applied at the front-end and the backend.
In this recipe, we will define a data dictionary component to implement the following validation logic and use AlchemyJ JavaScript library to validate a web form:
Name – String, mandatory
Date of Birth – Date, optional
Gender – String, only accepts F or M, automatically converted to upper case
Customer Level - Integer, mandatory, default is 3, must be between 1 and 4
Telephone - String, 15 characters max
Exporting data dictionary configuration
Refer to Setting up a data dictionary to set up the data dictionary component.
Include the Data Dictionary Worksheet name in Related Worksheets section of Java API Class Worksheet.
Build the project by running AlchemyJ menu AlchemyJ -> Build Project
All configuration details in the Data Dictionary component will be exported in JSON format and saved in datadict.repository.js in the output directory. Both ES5 and ES6 Language Standard are supported.
Using AlchemyJ Javascript library to validate UI fields
Define an HTML page to include the data item listed in the Data Dictionary component. AlchemyJ Java Script Library (it can be found in the AlchemyJ Compiler installation folder) and datadict.repository.js need to be included in the page as well.
<script src="AlchemyJ/AlchemyJ.js"></script>
<script src="AlchemyJ/datadict.repository.js"></script>
- Use datadict.process to validate the input values, below is some sample code to trigger the validation. Sample JS to process the validation to be included in the the submit button.
// Sample functions to process the validation
$(".submit").click(function(){
var form=$(this).closest(".aj-form");
form.find("input[name]").each(function(){
$(this).blur();
});
$AlchemyJ.dataDict.process(form.attr("formid"), getJson(form), false)
.then(showMessage);
})
- Build a function to check the validation result.
// Sample functions to concatenate the error messages
function showMessage(data){
if(data.validationResult){
popupMsg("pass");
}else{
var messageList=[];
for(var dataItemName in data.details){
var errorMessage=data.details[dataItemName].errorMessage;
if(errorMessage && errorMessage.length){
messageList=messageList.concat(errorMessage);
}
}
popupMsg(messageList.join("<br/>"));
}
}
- The error message would be shown to the user on the web page as shown below.