Validation in Radio button options in Checkout UI extension

Validation in Radio button options in Checkout UI extension

Ponmari
Shopify Partner
20 1 4

I have Added custom fields using checkout UI extension. And I want to add validation to it, so far I have done required validation rule for text field , text area, checkbox, and some more too. 

But when I try to show required validation error message in Multi checkbox and Radio option field , error does not show like other fields custom error message.

 

Do these components support error attribute ??

Documentation Does not provide error attribute for ChoiceList Component.

 

https://shopify.dev/docs/api/checkout-ui-extensions/2024-01/components/forms/choicelist

 

Can someone give solution for me on how to add validation error message below the respective fields in ChoiceList components.

 

My code for  custom  Multi checkbox field , error attribute is not working , even though blocking progress is working correctly. 

 

import React, { useState } from "react";
import {
  reactExtension,
  Choice,
  ChoiceList,
  InlineStack,
  useTranslate,
  useApi,
  useSettings,
  useApplyMetafieldsChange,
  useMetafield,
  useExtensionCapability,
  useBuyerJourneyIntercept
} from '@shopify/ui-extensions-react/checkout';

export default reactExtension(
  'Checkout::Dynamic::Render',
  () => <Extension />,
);


var checkboxValues=[];
 let values;
 let check;

function Extension() {
  const translate = useTranslate();
  const { extension } = useApi();
  const {label: merchantLabel,options:merchantOptions,variant:merchantVariant,metafieldnamespace:merchantMetaname,metafieldkey:merchantMetakey,required:merchantRequired,customerror:merchantcustomError} = useSettings();
  const required= merchantRequired ?? "Yes";
  const customerror= merchantcustomError ?? "This field is required";
  const [error, setError] = useState('');
  const [selected, setSelected] = useState("");
 const label = merchantLabel ?? 'Section the option';

 const variant = merchantVariant ?? 'base';

 const metafieldnamespace= merchantMetaname ?? "multicheckbox";
 const metafieldkey= merchantMetakey ?? "custommulticheckbox";
 const canBlockProgress = useExtensionCapability("block_progress");


 const residentIdState = useMetafield({
   namespace: metafieldnamespace,
   key:  metafieldkey,
 });

 const applyMetafieldsChange = useApplyMetafieldsChange();

// if merchantOptions empty(merchant does'nt entry any option for the select )
//  default dummy options 
 let options = merchantOptions ?? "Option1\nOption2\nOption3\nOption4\nOption5\nNone of the above\n"; 
 
 options = options.split("\n");   // newline string to array conversion

 options = options.filter(elm => elm);  // Filter array for empty element

 useBuyerJourneyIntercept(({ canBlockProgress }) => {
  // Validate that the age of the buyer is known, and that they're old enough to complete the purchase
  if (canBlockProgress && !isTextSet() && required==='Yes') {
    return {
      behavior: "block",
      reason: "Checkbox need to be checked",
      errors: [
        {
          // Show a validation error on the page
          message:
            "Please select any one checkbox",
        },
      ],
      perform: (result) => {
        // If progress can be blocked, then set a validation error on the custom field
        if (result.behavior === "block") {
          setError(customerror);
          // jQuery( "<p>Test</p>" ).insertAfter( "._1fragemkj _1fragemir _1fragemmn" );

        }
      },
    };
  }

  return {
    behavior: "allow",
    perform: () => {
      // Ensure any errors are hidden
      clearValidationErrors();
    },
  };
});

function isTextSet() {
   console.log(selected);
   
     check=options[selected];
    
      checkboxValues.push(check);
    
       values= checkboxValues.toString();
     
      const insert = applyMetafieldsChange({
        type: "updateMetafield",
        namespace: metafieldnamespace,
        key: metafieldkey,
        valueType: "string",
        value:values,
        ownerResource: 'order',
        ownerId: "gid://shopify/AppInstallation/452423745792",
      }).then(response => {
        console.log('multi checkbox Metafield changes applied:', response);
      })
      .catch(error => {
        console.error('Error applying metafield changes:', error);
      });

   
   return selected !=="";
}


function clearValidationErrors() {

setError("");
}
 
    return (
      <InlineStack>     
     <ChoiceList
        name="base-multiple"
        value={[]} 
        variant={variant}
        onChange={setSelected} 
        required={canBlockProgress} 
        error={error}
        onInput={clearValidationErrors}
      >
        {options.map((option, index) => {
  return(
    <><Choice id={index} >{option}</Choice></>
    )}
)}
      </ChoiceList>
    </InlineStack>
    
  );
}

 

 

Replies 0 (0)