i am trying to set regex pattern in input field attribute and use js to validate it.. but somehow it’s not working..
if i use same pattern directly on js it works.. but not through the attribute..
here is my html code:
<input type="text" name="tPhoneNumber" id="tPhoneNumber" style="width:90%;" data-name="Phone Number" data-group="NewEntry" data-required="y" data-pattern="/^+44[d]{10}$/" />
and here is the js code:
//this works
if (/^+44[d]{10}$/.test(inputs[i].value))
{
console.log("matched");
}
else
{
console.log("not matched");
}
//this does not works, it's always failed regardless whether the text box has correct value or not
if(!inputs[i].value.match(inputs[i].dataset.pattern))
{
var msg = `Invalid data entered in "${inputs[i].dataset.name}" field!<br/>You have entered = ${inputs[i].value}`;
return ShowError(msg);
}
what i am doing wrong here?
thanks in advance
best regards
2
Answers
Since data attribute inside your input is just string, not a
RegExp
object, you should remove slashes/
at start and end of its value:data-pattern="^+44[d]{10}$"
Your in-code regex works because you are using a regular expression literal, which creates an instance of
RegExp
. A regular expression literal is a regular expression placed between forward-slashes (optionally followed by flags).Your attribute pattern does not work because custom data attributes are represented as strings in JavaScript.
So when you call
.match(dataset.pattern)
, you pass a string instead of aRegExp
object. The string converts to aRegExp
object.The leading and trailing forward-slashes are JS syntax for creating a
RegExp
object, sodata-pattern
and your JSRegExp
are not the same.data-pattern
should only represent the regular expression, so that it will be converted correctly; remove the forward-slashes ofdata-pattern
.