Viewing 5 reply threads
  • Author
    Posts
    • #2151
      Jason
      Keymaster

      Greetings!

      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!

    • #2152
      Jason
      Keymaster

      I 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?

    • #2154
      Steve
      Keymaster

      @jason– On the page you referred to, we have an example with the callback function.

      The filter adds the rule… the rule calls the callback.

    • #2155
      Steve
      Keymaster

      @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',
          )
        )
      ));
      
    • #2164
      Jason
      Keymaster

      That’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!

    • #2166
      Steve
      Keymaster

      @jason– added to docs. Closing ticket.

Viewing 5 reply threads
  • The topic ‘How to perform custom validation’ is closed to new replies.