0

I have a custom method for validating Youtube links, everything works great but it's still firing when the input is left blank.

How can I not have the custom method fire if the input is left blank, but still validate if something is inputted?

Method

jQuery(function() {
  var youtubePattern = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;

  jQuery.validator.addMethod("youtubeVideo", function(value) {
      return youtubePattern.test(value);
  }, "Must be a valid Youtube video");
});

Validation

$( "#addPostsForm" ).validate({
 rules: {
    post_video: {
        youtubeVideo: true
    }
}
Sparky
  • 98,165
  • 25
  • 199
  • 285
Brad
  • 99
  • 11
  • 1
    [Look at the examples in the documentation](https://jqueryvalidation.org/jQuery.validator.addMethod/). All three have one bit of code in common that answers your question. `return this.optional(element) || youtubePattern.test(value);` – Sparky Dec 16 '17 at 06:31
  • @Sparky adding that makes all the validation stop working. – Brad Dec 16 '17 at 22:01
  • Your problem is that you're not passing the `element` argument into your custom `addMethod` function. `function(value)` ~ Otherwise working fine with `function(value, element)`: https://jsfiddle.net/zp0yg74a/ – Sparky Dec 17 '17 at 00:13
  • @Sparky Yup that was it, thanks! – Brad Dec 17 '17 at 15:59

1 Answers1

-1

Why not simple add a check for the value length inside the validator function?

jQuery(function() {
  var youtubePattern = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;

  jQuery.validator.addMethod("youtubeVideo", function(value) {
      if (value.length == 0){
          return false;
      }
      return youtubePattern.test(value);
  }, "Must be a valid Youtube video");
});
l4ci
  • 95
  • 3
  • 10