Input with pattern not working

On the admin widgets.php page I am trying to setup a pattern on an input to only allow digits. If I enter an invalid character like a non-digit it still accepts it and when I save the Widget with an invalid character in the input it also accepts it.

Here is the pattern I am using:

required pattern="[0-9]{3}"

Here is the input markup:

input type="text" value="200" maxlength="3" required="" pattern="[0-9]{3}" title="Three or less digit numbers only" class="widefat" id="widget_categories_v2-4-menu_width" name="widget_categories_v2[4][menu_width]"

Not sure why but when I inspect the input in Chrome it adds ="" to the require field shouldn't it just be required pattern="[0-9]{3}", is that relevant?

When I hit the 'enter' key it does notify the user of inputs that are malformed which is good. But again I hoping while typing in or hitting the Save button on the widget that it will not accept a malformed input. Do I need to add this logic to some javascript?

Its important that I get this working as the input field is used for setting the width of an element, and can't have non digits in there.

thanks

Topic input widget-text Wordpress

Category Web


Most likely because widgets are saved via AJAX, and, as far as I'm aware, the submit handler will bypass any HTML5 input rules unless they are explicitly checked with JavaScript.

Your best bet is to validate/sanitize the data server-side, and pass back any messages if there is an input error.

Chrome adding ="" is just a nuance of the console - it's not your actual markup, but the interpreted DOM.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.