Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pattern.test is not a function

I really dont understand why the following code doesnt match the regex

$val = "12/11/2012";
$opts = {"rule" : "required|format", "format" : {"pattern" : /^\d{1,2}\/\d{1,2}\/\d{4}$/, "errorMsg" : "Invalid date. Allowed allowed: mm/dd/yyyy"}}; 

if(rule=="format" && typeof $opts.format.pattern==="string") {
    try {
       var pattern = (typeof $opts.format.pattern==="object") ? $opts.format.pattern : new Regex($opts.format.pattern, "g");
       if(pattern.test($val)) { // $val contains 12/11/2012
            alert("Invalid Date!"); // Shows invalid format
       }
    } catch(err){
       alert(err.message); // shows pattern.test is not a function
    }
}
like image 414
Steve Avatar asked Nov 12 '22 15:11

Steve


1 Answers

The problem is that $opts.format.pattern is not a string, it's a RegEx object.

So this will work:

var $val = "12/11/2012";
var $opts = {"rule" : "required|format", "format" : {"pattern" : /^\d{1,2}\/\d{1,2}\/\d{4}$/, "errorMsg" : "Invalid date. Allowed allowed: mm/dd/yyyy"}}; 

if ($opts.format.pattern instanceof RegExp) {
  try {
    var pattern = $opts.format.pattern;
    if(!pattern.test($val)) {
      alert("Invalid date");
    } else {
      alert("Valid date");
    }
  } catch(err){
    alert(err.message); // shows pattern.test is not a function
  }
}
like image 69
mccannf Avatar answered Nov 15 '22 06:11

mccannf