I’ve solved this exact mobile validation issue multiple times. Let me address the three critical areas: mobile event handling differences, proper form validation implementation, and cross-browser testing requirements.
Mobile Event Handling: Mobile browsers handle form submissions through different event pipelines than desktop. Touch interactions trigger different event sequences, and some mobile browsers use native form submission that bypasses JavaScript event listeners. Your addEventListener approach fails because HubSpot forms on mobile use their own submission handler that fires before your event listener.
The solution is to use HubSpot’s Forms API instead of DOM events:
window.addEventListener('message', function(event) {
if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmit') {
// Validation happens too late here
}
});
That’s still too late. Use the onBeforeFormSubmit hook:
hbspt.forms.create({
portalId: 'YOUR_PORTAL_ID',
formId: 'YOUR_FORM_ID',
onBeforeFormSubmit: function($form) {
const phone = $form.find('input[name="phone"]').val();
if (!validatePhone(phone)) {
return false; // Prevents submission
}
}
});
Form Validation Best Practices: Implement multi-layer validation for data quality. Use HTML5 attributes for basic validation that works everywhere:
<input name="phone" type="tel"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Then enhance with JavaScript for complex rules. For mobile specifically, validate on blur events too, not just submit:
document.querySelector('input[name="phone"]').addEventListener('blur', function() {
validatePhone(this.value);
displayValidationMessage(this);
});
Cross-Browser Testing: Mobile validation requires testing on actual devices, not just emulators. iOS Safari, Chrome Mobile, and Samsung Internet all handle forms differently. Key differences:
- iOS Safari: Aggressive form autofill interferes with validation
- Chrome Mobile: Touch events fire in different order than mouse events
- Samsung Internet: Custom form controls bypass standard validation
Create a testing matrix covering iOS 14+, Android 10+, and major mobile browsers. Use BrowserStack or similar for comprehensive coverage.
Implement feature detection rather than browser detection:
const isTouchDevice = 'ontouchstart' in window;
if (isTouchDevice) {
// Use touch-optimized validation timing
}
For your specific case, refactor to use HubSpot’s form lifecycle hooks and add HTML5 validation as baseline. Test the validation flow on at least three physical devices before deploying. This ensures consistent data quality regardless of how users access your forms.
Also add server-side validation as ultimate fallback. Client-side validation improves UX but never rely on it solely for data quality. HubSpot workflows can validate and flag bad submissions for cleanup.