我的验证码有什么问题?(正则表达式很好)

What is wrong with my validation code? (Regex is fine)

本文关键字:正则表达式 很好 问题 验证 什么 我的      更新时间:2023-09-26

我在这里使用正则表达式jQuery Youtube URL Validation with regex

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

在这里工作正常 https://regex101.com/#javascript

但是我的代码不起作用 - 我正在使用jquery.validate.min.js和其他方法.js

我下面的代码适用于其他正则表达式,但这个代码不起作用,它总是说无效:

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"
        }
    }

谢谢

除非必须,否则不要使用字符串和RegExp()构造函数。使用本机正则表达式文本:

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

字符串词法语法还将反斜杠字符识别为元字符,因此您必须通过加倍来引用它们。如果您将表示法用于正则表达式文本,则不必担心这一点。