Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS Regex Pattern Used In Data-XXX Attributes Not Working

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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}$" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading