how to apply different validation rules on basis of value in another field

Neelu90
Tera Contributor

Neelu90_1-1712321578062.png

 

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

1 REPLY 1

Community Alums
Not applicable

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 CountryID TYPENational ID
United KingdomPassport123

 

1. Create these choices in sys_choice table:

sys_choice.png

 

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.