0

I am trying to have my dynamically generated text inputs only allow for digits and an optional decimal point in between. I am using the attribute but the inputs are still unresponsive to the RegEx.

var howMuch = $("<input>").attr("type", "text").attr("name", "howMuch").attr("pattern", "([0-9]+(\.[0-9]+)?)").prop("required", true);

The HTML generates like so: HTML

PLEASE do not mark this question as duplicate, none of the existing similar answers are already using the 'required' attribute

2
  • 1
    Should be "([0-9]+(\\.[0-9]+)?)" to account for string metacharacter interpretation. "([0-9]+(\.[0-9]+)?)" is exactly the same as "([0-9]+(.[0-9]+)?)". Commented Aug 20, 2018 at 14:51
  • Neither of those expressions solved my issue. Alphabetical inputs are still being added. Commented Aug 20, 2018 at 14:55

1 Answer 1

1

Pointy answer applies. Also, pattern attributes only works at form validation time. In other words, user is able to type in whatever he wants. Only when he presses submit, pattern attribute is taken into consideration. If you want a realtime feedback to user you should listen to change events and manually trigger the form validate method. Or you can use the keydown event to prevent some characters to be accepted as input.

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

1 Comment

Think I'm going to use keydown. Thank you for your answer!

Your Answer

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