Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Version History

Version 1 Current »

The Send2CRM website client deliberately avoids exposing specific error details when a form submission fails. Instead a configurable generic message is displayed. This page shows how to override that message.

Send2CRM does generate more detailed client-side error messages. These can be viewed in the browser console where error-level messages are logged on submission failure. They can also be used to display dynamic validation errors to website visitors as shown below.

Implement your code in a handler for a window event such as load or pageshow.

// Optional: regexes to match error text with short code substitutions for minimal output.
const ERR_CODES = [
	[/time/i, 'TIME_RESTR'],
	[/identifier/i, 'IDENT_MISSING'],
	[/fields/i, 'FIELD_MISSING'],
	[/recaptcha/i, 'CAPTCHA_MISSING'],
	// Add a catch-all.
	[/.*/, 'GEN_ERR'],
];

// Attach to all form elements automatically processed by Send2CRM.
document.querySelectorAll(send2crm.settings.formSelector).forEach(frm => {
	// Listen for the Send2CRM form submit event which will be fired with error information when a submission fails.
	frm.addEventListener('send2crmFormSubmit', (evt) => {
		/* evt.detail: {
			isSuccess: true|false,
			error: '<populated with error text on failure>',
		} */
		
		if (!evt.detail.isSuccess) {
			// Get the first matching error code.
			let errCode = ERR_CODES.filter(e => evt.detail.error.match(e[0])).shift()?.[1];
			
			// Get the submit button, we use this as the invalid element for general form errors.
			let frmSubmit = frm.querySelector('[type="submit"]');
			if (errCode && frmSubmit) {
			
				// Append the error code to the end of the default message.
				// If you don't mind displaying the full message to visitors you could simply use evt.detail.error here.
				let errMsg = `${send2crm.settings.formFailMessage} [${errCode}]`;
				
				// Apply the error to the submit element, this will override the default Send2CRM message.
				frmSubmit.setCustomValidity(errMsg);
				frmSubmit.reportValidity();
				
				// Note Send2CRM will automatically clear the form invalidity after 5 seconds so re-submission attempts are possible.
			}
		}
	});
});

  • No labels