Replies: 1
I’m trying to add some additional validation to the urls submitted on my registration form, and while the code below does properly prevent form submission if the urls aren’t set properly, the error messages aren’t appearing beside the appropriate fields. I’m not sure if I’ve just got the wrong hooks, if it’s a problem with the multi-step/paginated setup, or some other issue. Some tips on how to revise this to properly filter my urls would be appreciated
add_filter( 'forminator_custom_form_submit_errors', 'custom_url_validation', 10, 3 );
function custom_url_validation( $submit_errors, $form_id, $field_data_array ) {
// Target specific form by ID
$target_form_id = 140100;
if ( $form_id != $target_form_id ) {
return $submit_errors;
}
// Define the fields to validate
$platform_url_fields = array( 'url-2', 'url-3', 'url-4', 'url-5' );
foreach ( $platform_url_fields as $field_name ) {
$url = '';
foreach ( $field_data_array as $field_data ) {
if ( $field_data['name'] === $field_name ) {
$url = $field_data['value'];
break; // Exit inner loop after finding the URL
}
}
if ( empty( $url ) ) {
continue; // Skip validation for empty URL fields
}
// Generic URL validation
if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
$submit_errors[ $field_name ] = __( 'Please enter a valid URL.', 'your-text-domain' );
continue; // Skip to the next field after validation failure
}
// Platform-specific validation
switch ( $field_name ) {
case 'url-2':
if ( strpos( $url, 'instagram.com' ) === false ) {
$submit_errors[ $field_name ] = __( 'Please enter a valid Instagram URL.', 'your-text-domain' );
}
break;
case 'url-3':
if ( strpos( $url, 'facebook.com' ) === false ) {
$submit_errors[ $field_name ] = __( 'Please enter a valid Facebook URL.', 'your-text-domain' );
}
break;
case 'url-4':
if ( strpos( $url, 'linkedin.com' ) === false ) {
$submit_errors[ $field_name ] = __( 'Please enter a valid LinkedIn URL.', 'your-text-domain' );
}
break;
case 'url-5':
// Add your platform-specific logic for 'url-5'
if ( strpos( $url, 'x.com' ) === false ) {
$submit_errors[ $field_name ] = __( 'Please enter a valid X URL.', 'your-text-domain' );
}
break;
default:
// Optional: Handle unexpected cases
$submit_errors[ $field_name ] = __( 'Unexpected field encountered.', 'your-text-domain' );
break;
}
}
return $submit_errors;
}