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
>Solution :
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}$"
var input = document.getElementById('tPhoneNumber');
//this works
if (/^\+44[\d]{10}$/.test(input.value))
{
console.log("matched");
}
else
{
console.log("not matched");
}
//this should works too
if(!input.value.match(input.dataset.pattern))
{
console.log(`Invalid data entered in "${input.dataset.name}" field!<br/>You have entered = ${input.value}`);
}
<input type="text" name="tPhoneNumber" id="tPhoneNumber" value="+440123456" style="width:90%;" data-name="Phone Number" data-group="NewEntry" data-required="y" data-pattern="^\+44[\d]{10}$" />