Hello,
I would like to create a field where the user can embed a youtube video.
The only validation I see is Valid url.
I would like to use regex validation to make sure its a youtube video.
How can I do this?
Thanks
I can suggest a regex pattern to match youtube video URLs:
^(https?://)?(www\.)?(youtube\.com|youtu\.?be)/.+$
Where and how you use it depends on whether your users will be entering data in the WordPress back end, or via front-end Toolset Forms, in which case you would still have the question of whether you intend to validate the input in the form itself (with custom JavaScript) or on the server upon submission (with custom PHP, using the cred_form_validate hook).
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
Thanks Nigel,
The data will be entered by the user on a toolset form that will be available to him after crearing an account and logging in
Jacques
Hey there,
Here's an example of how you could do it using the suggestion by Nigel.
You'd need to change the form ID and the field name.
Moreover, please feel free to change it to adapt to your own needs.
add_filter('cred_form_validate','my_validation',10,2);
function my_validation($field_data, $form_data)
{
//field data are field values and errors
list($fields,$errors)=$field_data;
//validate if specific form
if ($form_data['id']==1)
{
//check wpcf-video-url value
if (!preg_match('/^(https?://)?(www\.)?(youtube\.com|youtu\.?be)/.+$', $fields['wpcf-video-url']['value']))
{
//set error message for wpcf-video-url
$errors['wpcf-video-url']='The url is not a valid Youtube video';
}
}
//return result
return array($fields,$errors);
}
Please let us know if we can help you further.
Best,
Mateus