Skip to content

Instantly share code, notes, and snippets.

@Acephalia
Last active December 21, 2023 22:22
Show Gist options
  • Save Acephalia/51f344c2a19448fa27e7ac5f78fd95ab to your computer and use it in GitHub Desktop.
Save Acephalia/51f344c2a19448fa27e7ac5f78fd95ab to your computer and use it in GitHub Desktop.
Divi Contact Form Field URL Validation
<script>
jQuery(document).ready(function($) {
// Get the form field. Change #et_pb_contact_url_0 to match your target field
var urlField = $('#et_pb_contact_url_0');
var form = $('form');
// Regular expression to validate URLs
var urlRegex = /^(ftp|http|https):\/\/[^ "]+$/;
// Flag to track validation status
var isValid = false;
// Function to validate the URL
function validateUrl() {
// Get the value of the URL field
var urlValue = urlField.val();
// Check if the entered value matches the URL pattern
isValid = urlRegex.test(urlValue);
// Display an error message if invalid
if (!isValid) {
alert('Please enter a valid URL.');
}
}
// Attach a function to the change event (field loses focus or value changes)
urlField.change(function() {
validateUrl();
});
// Attach a function to the focusout event (user attempts to leave the field)
urlField.focusout(function() {
// If not valid, keep focus on the field
if (!isValid) {
urlField.focus();
}
});
// Prevent form submission on Enter key press
form.keypress(function(e) {
if (e.which === 13) {
e.preventDefault();
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment