how to apply different validation rules on basis of value in another field
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-05-2024 05:52 AM
I have a requirement to validate(Number of characters and should start with <str>) National ID on the basis of Home Country and ID type and there are 130 combination of Country and ID Type. Is there any way to apply different validation rules on basis of value in home country and ID type
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-07-2024 12:31 AM
Hi @Neelu90 ,
I will share one solution for this. In my case, I created 3 fields above in the Incident form. The National ID will have the prefix decided by both the Home Country and ID TYPE fields.
For example:
Home Country | ID TYPE | National ID |
United Kingdom | Passport | 123 |
1. Create these choices in sys_choice table:
2. Create onChange client script on National ID field:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var country = g_form.getValue('u_home_country');
var id = g_form.getValue('u_id_type');
var combinedVal = country + "_" + id;
var ga = new GlideAjax('validateHelper'); //this is the script include
ga.addParam("sysparm_name", "validateNationalID"); //this is the function
ga.addParam("sysparm_input", combinedVal); // Home country_ID type
ga.addParam("sysparm_nationalID", newValue); // National Id
ga.getXMLAnswer(getResponse);
function getResponse(response) {
if (response == 'false') {
g_form.addErrorMessage("Wrong National ID");
g_form.clearValue('u_national_id');
}
}
}
3. Create a Script include named "validateHelper" with Client callable is true;
var validateHelper = Class.create();
validateHelper.prototype = Object.extendsObject(AbstractAjaxProcessor, {
validateNationalID: function() {
var input = this.getParameter('sysparm_input');
var value = this.getParameter('sysparm_nationalID');
var choiceGR = new GlideRecord('sys_choice');
choiceGR.addQuery('name', 'incident');
choiceGR.addQuery('element', 'national_id');
choiceGR.addQuery('label', input);
choiceGR.setLimit(1);
choiceGR.query();
if (choiceGR.next()) {
if (value.startsWith(choiceGR.dependent_value.toString())) {
return true;
}
}
return false;
},
type: 'validateHelper'
});
4. Create 2 onChange Client scripts on the field Home Country and ID TYPE with the same script (will clear National ID value whenever these two fields change):
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading) {
return;
}
g_form.clearValue('u_national_id');
}
If you have many combinations, you can prepare the data in the excel file then use the transform map to create them all at once.
Alternatively, instead of using sys_choice table, you can use the System property to store the combination.