Jquery 正则表达式验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10038941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:45:13  来源:igfitidea点击:

Jquery RegEx Validation

jqueryregexvalidation

提问by user1265533

I am wanting to check if an input field has the attribute "pattern" and if so, preform a regex check aganst said pattern.I know this is already done by HTML5, but I am wanting to handle the event myself. I am receiving this error: Uncaught TypeError: Object a-zA-Z has no method 'test'

我想检查输入字段是否具有“模式”属性,如果是,则执行正则表达式检查 ganst 所述模式。我知道这已经由 HTML5 完成,但我想自己处理该事件。我收到此错误:Uncaught TypeError: Object a-zA-Z has no method 'test'

 ///Check Perform Reg///////////////////////////////////////////////////////
         if ($(this).attr("pattern")) {
             var reg = $(this).attr("pattern");
             var currentValue = $(this).val();


             if (reg.test(currentValue)) {
                 $(this).after($error.clone().text("Invalid Input.Try Again."));
                 $(".error:hidden").fadeIn("slow");
                 hasError = true;
                 return false;
             }

             }
        ///////////////////////////////////////////////////////////////////////////

Still no luck,

还是没有运气,

also here is my html:

这里也是我的 html:

<div>
    <input class="formInput" name="First Name" pattern="^[A-Za-z_-][A-Za-z0-9_-]*$" type="text"  id="frmFirst" min="2" maxlength="30"  required="required"/>
    <span>First Name</span>
</div>

回答by irfanmcsd

Normally regular expression with javascript / jquery handle like

通常带有 javascript / jquery 句柄的正则表达式,如

var reg = /pattern/;
if (reg.test($(this).val())) {
    // perform some task
}

回答by deezy

As already mentioned by others you need to use an object instead of the string returned by the jQuery attr() method. You can see the difference between the two here.

正如其他人已经提到的,您需要使用对象而不是 jQuery attr() 方法返回的字符串。你可以在这里看到两者之间的区别。

Will return "string":

将返回“字符串”:

var reg = $(this).attr("pattern");
console.log(typeof reg)

Will return with "object":

将返回“对象”:

var reg = new RegExp($(this).attr("pattern"));
console.log(typeof reg);

So if you replace:

所以如果你更换:

var reg = $(this).attr("pattern");

With:

和:

var reg = new RegExp($(this).attr("pattern"));

The Uncaught TypeError: Object a-zA-Z has no method 'test'error will disappear

未捕获的类型错误:对象A-ZA-Z不具有方法“测试”错误将消失

...but your validation still won't work very well. Your conditional logic says if the regex test returns TRUE then handle an error:

...但您的验证仍然不会很好地工作。您的条件逻辑表示,如果正则表达式测试返回 TRUE,则处理错误:

if (reg.test(currentValue)) {
    //error handling
}

Instead it should handle an error if the test returns FALSE:

相反,如果测试返回 FALSE,它应该处理错误:

if (!reg.test(currentValue)) {
    //error handling
}

This should work for you.

这应该对你有用。

回答by rrtx2000

You can try something like this. It will alert "var2 failed".

你可以尝试这样的事情。它将警告“var2 失败”。

var var1 = "1";
var var2 = "A";
var myRegEx = new RegExp('[0-9]+'); //make sure the var is a number

if (var1 != myRegEx.exec(var1)) {
    alert("var1 failed");
}

if (var2 != myRegEx.exec(var2)) {
    alert("var2 failed");
}

回答by Qasim Bataineh

Below is the proper way to validate a text-box based on a regular Expression using Jquery in MVC. Please note that this expression is made to validate multi email addresses in one string:

下面是在 MVC 中使用 Jquery 基于正则表达式验证文本框的正确方法。请注意,此表达式用于验证一个字符串中的多个电子邮件地址:

      var emailReg = new RegExp(/^([A-Z0-9.%+-]+@@[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+@@[A-Z0-9.-]+.[A-Z]{2,6}))*$/i);
      var emailText = $('#email').val();

      if (!emailReg.test(emailText)) {
          alert('Wrong Email Address\Addresses format! Please reEnter correct format');
            return false;
        }
    }

回答by Qtax

A string is not a RegExpobject. You could use something like:

字符串不是RegExp对象。你可以使用类似的东西:

var reg = new RegExp($(this).attr("pattern"));