0

I am using the regex here jQuery Youtube URL Validation with regex

^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$

It works fine here https://regex101.com/#javascript

But my code is not working- I am using jquery.validate.min.js and additional-methods.js

My code below works fine with other Regexes but with this one is not working, it always says invalid:

var yt = new RegExp("^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$");

$("#submit-form").validate({

    // Specify the validation rules
    rules: {
        yturl: {
            required: true,
            minlength: 3,
            pattern: yt
        }

    },
    messages: {
        yturl: {
            pattern: "Wrong url"
        }
    }

Thanks

0

1 Answer 1

2

Don't use strings and the RegExp() constructor unless you have to. Use a native regular expression literal:

var yt = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;

The string lexical grammar also recognizes backslash characters as metacharacters, so you have to quote them by doubling them. If you use the notation for a regular expression literal, you don't have to worry about that.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.