skip to Main Content

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


  1. 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}$" />
    Login or Signup to reply.
  2. 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 a RegExp object. The string converts to a RegExp object.

    The leading and trailing forward-slashes are JS syntax for creating a RegExp object, so data-pattern and your JS RegExp are not the same.

    data-pattern should only represent the regular expression, so that it will be converted correctly; remove the forward-slashes of data-pattern.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search