Jquery RegEx Validation

前端 未结 5 474
情书的邮戳
情书的邮戳 2020-12-31 10:52

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 wan

相关标签:
5条回答
  • 2020-12-31 11:30

    Normally regular expression with javascript / jquery handle like

    var reg = /pattern/;
    if (reg.test($(this).val())) {
        // perform some task
    }
    
    0 讨论(0)
  • 2020-12-31 11:31

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

    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");
    }
    
    0 讨论(0)
  • 2020-12-31 11:35

    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.

    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

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

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

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

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

    This should work for you.

    0 讨论(0)
  • 2020-12-31 11:45

    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:

          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;
            }
        }
    
    0 讨论(0)
  • 2020-12-31 11:47

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

    var reg = new RegExp($(this).attr("pattern"));
    
    0 讨论(0)
提交回复
热议问题