0

I've got a problem while checking manually if my inputs are matching my patterns

Here is the function I use to check it

if (!$element.attr("pattern")) return true;

    let pattern = $element.attr("pattern");
    let exp;
    if (pattern.charAt(0) === "^") exp = new RegExp(pattern);
    else exp = new RegExp('^' + pattern + '$');

    if (exp.test($element.val())) return true;
    else {
        return false;
    }

I've checked without my ifelse which I use to set the var "exp", but the result is the same.

Here is the input I want to check

<input class="k-textbox cyclique-input-popin" type="text" pattern="^[0-9]+([,][0-9])?$"/>

It has a value of 0,25, and I want it to be abble to have value like that :

  • 1,25
  • 1,2
  • 0,2
  • 20
  • ...

Can have a "," or not, but can't have trailing zeros like 1,20

1 Answer 1

1

(1) Trailing zeros are permitted by your current pattern, and (2) the pattern only allows one digit to the right of the comma. You want something like this:

<input ... pattern="^[0-9]+(,[0-9]*[^0])?$">

Finally, your code can be simplified some:

let pattern = $element.attr('pattern');
if (!pattern) {
  return true;
}

let exp;
if (pattern[0] === '^') {
  exp = new RegExp(pattern);
} else {
  exp = new RegExp('^' + pattern + '$');
}

return exp.test($element.val()));

Let me know whether that gets you the result you're looking for. Good luck.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it matchs perfectly what I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.