function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jose Nogueira RodriguesJose Nogueira Rodrigues 

pre chat form component validation

Hi

I created a component for the Pre chat form and following the examples in the Developer Guide 18, it basically creates the inputs from the custom Pre chat form by collecting them as arrays. It all is inserted just fine in the pre chat form but, the values of the inputs, such as name, are assumed as valid when they are empty which should not be a valid input specially since they are "required" as part of their attributes.

I have been searching for a solution for this and the only solution that makes sence in my mind would be to add an external script that would validate the customer inputs, so in other words that script would be part of the Static Resources and I would call it with this method "embedded_svc.settings.externalScripts = ['validation']", although this script is being ignore for some reason and the custom"prechat.js" from Live agent keep giving me this message: Validation passed, firing chat request event.

Is there a better way to validate the inputs for them not to be empty before starting a live chat? Is there a particular reason as to why my script that is a Static Resource is being ignored?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Jose,

Greetings to you!

Please refer to the below links which might help you further with the above requirement.

https://salesforce.stackexchange.com/questions/107749/on-a-live-agent-pre-chat-form-how-can-i-make-a-field-mandatory

https://help.salesforce.com/articleView?id=snapins_chat_customize_prechat_form.htm&type=5

https://rajvakati.com/2017/11/02/live-agent-pre-chat-forms-with-validations/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Raj VakatiRaj Vakati
Refer this link  .. i guess you are ask is for snap ins and not for live agnet 



https://rajvakati.com/category/snap-ins/


 
<aura:component implements="lightningsnapin:prechatUI" description="Sample custom pre-chat component for Snap-ins. Implemented using Aura.">
    <!-- You must implement "lightningsnapin:prechatUI" for this component to appear in the "Pre-chat Component" customization dropdown in the Snap-ins setup -->
    
    <!-- Pre-chat field components to render -->
    <aura:attribute name="prechatFieldComponents" type="List" description="An array of objects representing the pre-chat fields specified in pre-chat setup."/>
    
    <!-- Handler for when this component is initialized -->
    <aura:handler name="init" value="{!this}" action="{!c.onInit}" />
    
    <!-- For Aura performance -->
    <aura:locator target="startButton" description="Pre-chat form submit button."/>
    
    <!-- Contains methods for getting pre-chat fields, starting a chat, and validating fields -->
    <lightningsnapin:prechatAPI aura:id="prechatAPI"/>
    
    <h2>Prechat form</h2>
    <div class="prechatUI">
        <div class="prechatContent">
            <ul class="fieldsList">
                <!-- Look in the controller's onInit function. This component dynamically creates the pre-chat field components -->
                {!v.prechatFieldComponents}
            </ul>
        </div>
        <div class="startButtonWrapper">
            <ui:button aura:id="startButton" class="startButton" label="{!$Label.LiveAgentPrechat.StartChat}" press="{!c.handleStartButtonClick}"/>
        </div>
    </div>
    
</aura:component>
 
({
    /**
     * On initialization of this component, set the prechatFields attribute and render pre-chat fields.
     * 
     * @param cmp - The component for this state.
     * @param evt - The Aura event.
     * @param hlp - The helper for this state.
     */
	onInit: function(cmp, evt, hlp) {
        // Get pre-chat fields defined in setup using the prechatAPI component
		var prechatFields = cmp.find("prechatAPI").getPrechatFields();
        // Get pre-chat field types and attributes to be rendered
        var prechatFieldComponentsArray = hlp.getPrechatFieldAttributesArray(prechatFields);
        
        // Make asynchronous Aura call to create pre-chat field components
        $A.createComponents(
            prechatFieldComponentsArray,
            function(components, status, errorMessage) {
                if(status === "SUCCESS") {
                    cmp.set("v.prechatFieldComponents", components);
                }
            }
        );
    },
    
    /**
     * Event which fires when start button is clicked in pre-chat
     * 
     * @param cmp - The component for this state.
     * @param evt - The Aura event.
     * @param hlp - The helper for this state.
     */
    handleStartButtonClick: function(cmp, evt, hlp) {
        hlp.onStartButtonClick(cmp);
    }
});
 
({
    /**
	 * Map of pre-chat field label to pre-chat field name (can be found in Setup)
	 */
    fieldLabelToName: {
        "First Name": "FirstName",
        "Last Name": "LastName",
        "Email": "Email",
        "Subject": "Subject",
        "Type": "Type",
        "Priority": "Priority"
    },
    
    /**
	 * Event which fires the function to start a chat request (by accessing the chat API component)
	 *
	 * @param cmp - The component for this state.
	 */
    onStartButtonClick: function(cmp) {
        var prechatFieldComponents = cmp.find("prechatField");
        var fields;
        
        // Make an array of field objects for the library
        fields = this.createFieldsArray(prechatFieldComponents);
        
        // If the pre-chat fields pass validation, start a chat
        if(cmp.find("prechatAPI").validateFields(fields).valid) {
            cmp.find("prechatAPI").startChat(fields);
        } else {
            console.warn("Prechat fields did not pass validation!");
        }
    },
    
    /**
	 * Create an array of field objects to start a chat from an array of pre-chat fields
	 * 
	 * @param fields - Array of pre-chat field Objects.
	 * @returns An array of field objects.
	 */
    createFieldsArray: function(fields) {
        if(fields.length) {
            return fields.map(function(fieldCmp) {
                return {
                    label: fieldCmp.get("v.label"),
                    value: fieldCmp.get("v.value"),
                    name: this.fieldLabelToName[fieldCmp.get("v.label")]
                };
            }.bind(this));
        } else {
            return [];
        }
    },
    
    /**
     * Create an array in the format $A.createComponents expects
     * 
     * Example:
     * [["componentType", {attributeName: "attributeValue", ...}]]
     * 
	 * @param prechatFields - Array of pre-chat field Objects.
	 * @returns Array that can be passed to $A.createComponents
     */
    getPrechatFieldAttributesArray: function(prechatFields) {
        // $A.createComponents first parameter is an array of arrays. Each array contains the type of component being created, and an Object defining the attributes.
        var prechatFieldsInfoArray = [];
        
        // For each field, prepare the type and attributes to pass to $A.createComponents
        prechatFields.forEach(function(field) {
            var componentName = (field.type === "inputSplitName") ? "inputText" : field.type;
            var componentInfoArray = ["ui:" + componentName];
            var attributes = {
                "aura:id": "prechatField",
                required: field.required,
                label: field.label,
                disabled: field.readOnly,
                maxlength: field.maxLength,
                class: field.className,
                value: field.value
            };
            
            // Special handling for options for an input:select (picklist) component
            if(field.type === "inputSelect" && field.picklistOptions) attributes.options = field.picklistOptions;
            
            // Append the attributes Object containing the required attributes to render this pre-chat field
            componentInfoArray.push(attributes);
            
            // Append this componentInfoArray to the fieldAttributesArray
            prechatFieldsInfoArray.push(componentInfoArray);
        });
        
        return prechatFieldsInfoArray;
    }
});

 
Jose Nogueira RodriguesJose Nogueira Rodrigues
Hi Rajamohan Yes that is what I am referring to, the prechat is created as expected but there is no restriction with empty inputs apparently since I can still start the chat without inserting anything. I was trying to use an external script within static resources but apparently it’s being ignored and within the “Helper” in this if statement: if(cmp.find("prechatAPI").validateFields(fields).valid; I added “&& cmp.find("prechatAPI").validateFields(fields) !== “” “ but that is also being ignored. I have tried different methods in both the component and the helper but nothing is actually restricting the user to proceed a conversation with the agent without inserting any inputs. Have you got a solution for this by any chance or am I calling the external scripts in the wrong way? Best, Jose Rodrigues Digital Operations Assistant — Mulberry 30 Kensington Church Street London, W8 4HA — E joserodrigues@mulberry.com Mulberry Company (Design) Limited (Co. No. 1954945). Reg. office: The Rookery, Chilcompton, Bath, Somerset, BA3 4EH. Registered in England and Wales
Matthew Millman 2Matthew Millman 2
Hey Jose,

I don't know if you ever figured this out. I had a similar requirement; the Case Subject field can't be null. This is what I ended up doing:
onStartButtonClick: function (cmp) {
        var prechatFieldComponents = cmp.find("prechatField");
        var fields;

        // Make an array of field objects for the library
        fields = this.createFieldsArray(prechatFieldComponents);

        // If the pre-chat fields pass validation, start a chat
        if(fields[3].value) {
            if (cmp.find("prechatAPI").validateFields(fields).valid) {
                cmp.find("prechatAPI").startChat(fields);
            } else {
                console.warn("Prechat fields did not pass validation!");
            }
        }else{
            window.alert("Please enter a subject");
        }
    }
In the above function, Case Subject was the 4th item on the PreChat form. So, with array notation, this becomes: if(fields[3].value) which will return true as long as that field has something in it. Hope this helps!
Jose Nogueira RodriguesJose Nogueira Rodrigues
Hi Matthew Thank you for your help, I actually managed to solve this issue.
Sai Lightning 10Sai Lightning 10
Hi Jose, 
Can you please help me with soulation, i am looking same validation in liveagent side.
Jose Nogueira RodriguesJose Nogueira Rodrigues
Hi Sai

Sorry I only now noticed your comment, I did manage to solve it but not quite the way that I wanted, it’s not clean code but it does more or less the trick, it might look a bit confusing to be honest, as soon as I notice it was working I just left it as it is. In sum the function that helped me the most is in the “Helper” section and the function is the following:

onStartButtonClick: function(cmp) {
        var prechatFieldComponents = cmp.find("prechatField");
        var apiNamesMap = this.createAPINamesMap(cmp.find("prechatAPI").getPrechatFields());
        var fields;
        // Make an array of field objects for the library.
        fields = this.createFieldsArray(apiNamesMap, prechatFieldComponents);
        
        var badInputs = new Array;
        for(var i = 0; i< fields.length; i++){
            var emailVal = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            if(i === 2){
                      emailVal.test(fields[i].value) ? fields[i].value : badInputs.push(i);
            }
            if(fields[i].value == undefined || fields[i].value == ''){
                badInputs.push(i);
            }           
        }
          // If the prechat fields pass validation, start a chat.
          if(cmp.find("prechatAPI").validateFields(fields).valid && badInputs.length == 0){
            cmp.find("prechatAPI").startChat(fields);
            } else {
                console.warn("Prechat fields did not pass validation!");
                return badInputs;
            }
    }
 
Shubham Bansal 45Shubham Bansal 45
Hi, Can we get object names with pre-chat fields? That either this field belongs to the case or contact?