Handling Validation in Smart Paste Button

25 Sep 202422 minutes to read

The Smart Paste Button can be configured to validate that all required input form fields have been pasted with content. If any form fields are empty, validation will be triggered to ensure that all necessary information is provided before proceeding.

import { SmartPasteButton, ChatOptions } from "@syncfusion/ej2-buttons";
import { TextArea, TextBox } from "@syncfusion/ej2-inputs";
import { Button, ChipList, ClickEventArgs, RadioButton } from "@syncfusion/ej2-buttons";
import { ComboBox } from "@syncfusion/ej2/dropdowns";
import {FormValidator, FormValidatorModel} from '@syncfusion/ej2-inputs';

let options: FormValidatorModel = {
    rules: {
        'bug-name': { required: true },
        'reporter-name': { required: true },
        'submit-date': { required: true },
        'bug-description': { required: true },
        'reproduce-steps': { required: true },
        'browser': { required: true }
    }
}
let formObject: FormValidator = new FormValidator('#form-element', options);

let externalSubmit: any = (): any => {
  // Validate the form from external validate method
  let formStatus: Boolean = formObject.validate();
  if (formStatus) {
    formObject.element.reset();
  }
};

document.getElementById('smart-paste')!.addEventListener('mousedown', externalSubmit);

let inputobj1: TextBox = new TextBox({
  placeholder: "What's the bug ?",
  floatLabelType: "Never",
});
inputobj1.appendTo("#bug-name");

let inputobj2: TextBox = new TextBox({
  placeholder: "Who is the reporter ?",
  floatLabelType: "Never",
});
inputobj2.appendTo("#reporter-name");

let inputobj3: TextBox = new TextBox({
  placeholder: "When it is reported ?",
  floatLabelType: "Never",
});
inputobj3.appendTo("#submitted-date");

let textArea1: TextArea = new TextArea({
  placeholder: "Describe a little about the bug.",
  rows: 2,
  floatLabelType: "Never",
});
textArea1.appendTo("#bug-description");

let textArea2: TextArea = new TextArea({
  placeholder: "Enter the repro steps here..",
  cols: 30,
  rows: 4,
  floatLabelType: "Never",
});
textArea2.appendTo("#reproduce-steps");

let radioButton: RadioButton = new RadioButton({
  label: "Low",
  name: "bug-priority",
  value: "low"
});
radioButton.appendTo("#radio1");

radioButton = new RadioButton({
  label: "Medium",
  name: "bug-priority",
  value: "medium",
  checked: true
});
radioButton.appendTo("#radio2");

radioButton = new RadioButton({
  label: "High",
  name: "bug-priority",
  value: "high",
});
radioButton.appendTo("#radio3");

const browserData: string[] = [
  'Chrome', 'Firefox', 'Safari'
];
let comboBoxObj: ComboBox = new ComboBox({
  popupHeight: '230px',
  dataSource: browserData,
  placeholder: 'Choose the browser',
});
comboBoxObj.appendTo('#browser');

// Initialize Button control.
let resetButton: Button = new Button({
  content: 'Reset',
  iconCss: "e-icons e-reset",
});
// Render initialized Button.
resetButton.appendTo('#reset');


const serverAIRequest = async (options: ChatOptions) => {
  let output: string | null = '';
  try {
    // console.log("input:", options);
    output = await (window as any).AzureAIRequest(options) as string;
    output = output.replace('END_RESPONSE', '')
    // console.log("Success:", output);
  } catch (error) {
    console.error("Error:", error);
  }
  return output;
};

// Initialize Smart Paste Button control.
let button: SmartPasteButton = new SmartPasteButton({
  content: 'Smart Paste',
  iconCss: "e-icons e-paste",
  aiAssistHandler: serverAIRequest
});
// Render initialized Smart Paste Button.
button.appendTo('#smart-paste');


// Property Pane Code

let bugPresets: string[] = [
  "Issue with the dropdown menu",
  "Trouble logging into the website",
  "Search functionality not working",
  "Images missing on the product page"
];

let bugReports: string[] = [
  `Hi, this is Alice. On July 3rd, I've come across a bug where the dropdown menu in the navigation bar doesn't close after selecting an item. I just navigated to the homepage, opened the dropdown menu in the navigation bar, clicked an item in the dropdown and then the issue occurred which happens only on Chrome. Though this doesn't seem like a serious/important bug, kindly look into it and resolve it. Regards, J Alice Abraham`,
  `Hey team, On May 2nd, K John Doe reported an issue where the login page refreshes instead of logging in when the user clicks the login button. This problem prevents users from accessing their accounts, making it a critical issue that needs immediate attention. The issue has been observed across all major browsers. To reproduce the issue, open any browser and navigate to the website's login page. Enter a valid username and password, then click the Login button.`,
  `Hi, Whenever I type something in the search bar and hit search, it doesn't return any results, even for items I know exist. This problem was noticed by Jane Smith on July 5th in FireFox browser. You can repro the issue by opening the site in the Firefox browser and navigate to the search bar. Type in any search term, including items that are known to exist, and click the search button. The search functionality fails to return any results, displaying an empty result set even for valid queries. This is quite important, but not urgent. Please look into it. Regards, M William Marker`,
  `Hello, When I selected the category option on the landing page and chose the electronics category, the images were missing on the product page. The placeholders are there, but no actual images are loading. This happens on all browsers. I reported this on July 3rd. It's not urgent, but it does affect the user experience. Regards, L Mike Johnson`
];

let copyContent: HTMLElement = document.getElementById('bug-report-text') as HTMLElement;
copyContent.innerHTML = bugReports[0];

let copyButton: Button = new Button({
  content: 'Copy',
  iconCss: "e-icons e-copy"
});
copyButton.appendTo('#copy-btn');

copyButton.element.onclick = async () => {

  await navigator.clipboard.writeText(copyContent.innerHTML);
  copyButton.content = "Copied";
  copyButton.iconCss = "e-icons e-check";
}

let chipList = new ChipList(
  {
    chips: bugPresets, selection: 'Single',
    selectedChips: [0],
    click: (e: ClickEventArgs) => {
      copyContent.innerHTML = bugReports[e.index as number] as string;
      chipList.selectedChips = e.index as number;
      copyButton.content = "Copy";
      copyButton.iconCss = "e-icons e-copy";
    }
  },
  '#chip-choice');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Floating Action Button</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="https://cdn.syncfusion.com/ej2/30.1.37/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/30.1.37/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="styles.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <script src="./azure_openai.js" type="module"></script>
    <style>
        .form-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 5px;
            width: 49%;
            margin: 0 auto;
        }

        .form-label {
            margin-bottom: 5px;
        }

        .form-input,
        .form-textarea,
        .form-select {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
            width: 100%;
        }

        .form-textarea {
            height: 80px;
        }


        .row-group {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .form-footer {
            display: flex;
            margin-top: 20px;
            justify-content: right;
            gap: 15px;
        }

        .form-group {
            display: grid;
            gap: 8px;
        }

        .single-row-group {
            display: grid;
            gap: 8px;
        }

        #bug-report-text {
            padding: 10px;
            margin: 15px 0px;
            background-color: #f3f3f3;
            border: 1px solid #ddd;
            border-radius: 5px;
            line-height: 1.5;
        }

        #reset,
        #smart-paste {
            border-radius: 20px;
        }
    </style>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>LOADING....</div>
    <div id='container'>
        <h2>Data Form with Syncfusion Smart Paste Button</h2>
        <form class="form-container" id="form-element">
            <div class="single-row-group">
                <label for="bug-name" class="e-form-label">Bug Name</label>
                <input type="text" id="bug-name" name="bug-name" class="form-input" />
            </div>
    
            <div class="row-group">
                <div>
                    <label for="reporter-name" class="e-form-label">Reporter</label>
                    <input type="text" id="reporter-name" name="reporter-name" class="form-input" />
                </div>
                <div>
                    <label for="submitted-date" class="e-form-label">Submitted Date</label>
                    <input type="text" id="submitted-date" name="submit-date" class="form-input" />
                </div>
            </div>
    
            <div class="form-group">
                <label for="bug-description" class="e-form-label">Bug Description</label>
                <textarea id="bug-description" class="form-textarea"></textarea>
            </div>
    
            <div class="row-group">
                <div style="display: flex;flex-direction: column;">
                    <label for="reproduce-steps" class="e-form-label">Reproduce Steps</label>
                    <textarea id="reproduce-steps" name="reproduce-steps" class="form-textarea"></textarea>
                </div>
                <div>
                    <label class="form-label">Bug Priority</label>
                    <div class="row">
                        <input id="radio1" type="radio">
                    </div>
                    <div class="row">
                        <input id="radio2" type="radio">
                    </div>
                    <div class="row">
                        <input id="radio3" type="radio">
                    </div>
                </div>
    
            </div>
    
            <div>
                <label for="browser" class="form-label">Select the browser</label>
                <input type="text" id="browser" name="browser" />
            </div>
    
            <div class="form-footer">
                <button type="reset" id="reset" class="form-button"></button>
                <button type="button" id="smart-paste" class="form-button"></button>
            </div>
        </form>
    
        <div class="col-lg-4 property-section">
            <div class="property-panel-section">
                <div class="property-panel-content">
                    <h4> Choose a preset below </h4>
                    <div class="chip-container">
                        <div id="chip-choice" aria-label="choiceChips"></div>
                    </div>
                    <div id="bug-report-text"></div>
                    <button id="copy-btn"></button>
                </div>
            </div>
        </div>    
    </div>
</body>

</html>
import { AzureOpenAI } from "https://cdn.jsdelivr.net/npm/openai@4.56.0/+esm";
 
//Warning: Do not expose your API key in the client-side code. This is only for demonstration purposes.

// Replace your Azure OpenAI endpoint, apiVersion, deployment and API key here
const endpoint = "AZURE_OPENAI_ENDPOINT";
const apiKey = "AZURE_OPENAI_API_KEY";
const deployment = "DEPLOYMENT_NAME";
const apiVersion = "API_VERSION";
 
const client = new AzureOpenAI({
    endpoint,
    apiKey,
    apiVersion,
    deployment,
    dangerouslyAllowBrowser: true
});
 
window.AzureAIRequest = async function (options) {
    try {
        const result = await client.chat.completions.create({
            messages: options.messages,
            model: "",
            top_p: options.topP,
            temperature: options.temperature,
            max_tokens: options.maxTokens,
            frequency_penalty: options.frequencyPenalty,
            presence_penalty: options.presencePenalty,
            stop: options.stopSequences
        });
        return result.choices[0].message.content;
    } catch (err) {
        console.error("Error occurred:", err);
    }
}