Based condition should not onSubmit the form else onSubmit

Siva82
Tera Expert

Hi Team,

I have a catalog item with an onSubmit client script that enforces some conditions. Currently:

  • The script enters the if block and shows the error message as expected.

  • However, when the conditions are not matched, the form does not submit as intended.

I have written the following script, but it’s not working properly. Could you please review and help fix it?

Thank you in advance for your support!

var allowSubmit = false; // declare globally

function onSubmit() {
    if (allowSubmit) {
        return true; // already validated, let submit continue
    }

    var locationSysId = g_form.getValue('current_work_location');
    var accessory = (g_form.getDisplayValue('choose_accessory') || '').toLowerCase();
    var hasYubikey = accessory.includes('yubikey');
    alert(hasYubikey);

    var ga = new GlideAjax('LocationSubmitValidator');
    ga.addParam('sysparm_name', 'getLocationData');
    ga.addParam('sysparm_location_id', locationSysId);

    ga.getXMLAnswer(function(answer) {
        var data;
        try {
            data = answer ? JSON.parse(answer) : null;
        } catch (e) {
            data = null;
        }

        // If no data, allow
        if (!data) {
            allowSubmit = true;
            g_form.submit();
            return;
        }

        // Block condition
        if (
            data.name && data.name.toLowerCase().includes('remote') &&
            (data.onsiteSupport == 0 || data.onsiteSupport === '0') &&
            (data.hardwareSelfService == 0 || data.hardwareSelfService === '0') &&
            !hasYubikey
        ) {
            g_form.addErrorMessage(
                'For Remote locations without onsite or hardware self-service support, a Yubikey request is mandatory.'
            );
            // do NOT call g_form.submit here
            return;
        }

        // Allow submit
        allowSubmit = true; // set before resubmitting
        g_form.submit();
    });

    return false; // always block original submit until callback finishes
}




Thank you
Siva
 
5 REPLIES 5

Mohammed8
Giga Sage

Hi @Siva82 

Mohammed8_0-1766410846323.png

 

I'm assuming since the error message is displayed, it confirms that the script is entering the if condition and the GlideAjax call is working as expected.  Why not put the highlighted code in screenshot above use else condition after if and check. not sure it will work but give it a try

 

Regrads,

Mohammed Zakir