Tagged: metabox, validation
- This topic has 5 replies, 2 voices, and was last updated 7 years, 6 months ago by
Steve.
-
AuthorPosts
-
-
August 5, 2014 at 11:04 am #2151
JasonKeymasterGreetings!
function validate_youtube_url($text) { $pattern = '/^https?:\/\/(www.)?youtu(be\.com|\.be)\/(watch\?v=)?([[:alnum:]_-]+)$/'; return preg_match($pattern, $text); } piklist('field', array( 'description' => 'Paste either the page or short url', 'type' => 'text', 'field' => 'design-video', 'label' => 'Video Url', 'columns' => 12, 'validate' => array( array( 'type' => 'youtube-url', 'callback' => 'validate_youtube_url', 'message' => 'Unrecognized youtube url' ) ) ));I’m attempting to validate a youtube url, but the validation never returns false. Am I misunderstanding how to use a custom callback?
Thanks!
-
August 5, 2014 at 11:07 am #2152
JasonKeymasterI just realized I was going about this all wrong. Oops! I have to add the validation first through the hook: https://piklist.com/user-guide/docs/piklist_validation_rules/
I guess I’m not understanding what the callback is for, then? At what point in the validation process is the callback called and for what purpose?
-
August 5, 2014 at 12:33 pm #2154
-
August 5, 2014 at 12:36 pm #2155
SteveKeymaster@jason– Since you’re validating with Regex, it’s even simpler:
add_filter('piklist_validation_rules', 'validate_youtube_url', 11); function validate_youtube_url() { $validation_rules = array( 'youtube-url' => array( 'rule' => "/^https?:\/\/(www.)?youtu(be\.com|\.be)\/(watch\?v=)?([[:alnum:]_-]+)$/" ,'message' => __('Unrecognized youtube url') ) ); return $validation_rules; }and your field:
piklist('field', array( 'description' => 'Paste either the page or short url', 'type' => 'text', 'field' => 'design-video', 'label' => 'Video Url', 'columns' => 12, 'validate' => array( array( 'type' => 'youtube-url', ) ) )); -
August 5, 2014 at 4:18 pm #2164
JasonKeymasterThat’s exactly what I ended up doing. Worked great!
I get the callback now. If it returns === true, then it’s valid; if it returns a string, that’s the error message. Might be a good idea to specify that in the docs. 😉
This can be closed. Thanks!
-
August 5, 2014 at 4:36 pm #2166
-
-
AuthorPosts
- The topic ‘How to perform custom validation’ is closed to new replies.