简体   繁体   中英

How to perform inline validation in Knockout on an input field

I want to allow the user to only enter postive numbers and numbers less then 100. How can i modify this input markup to get my required validation.

<input data-bind="value : $root.rootData.Page" class="form-control">

Edit: I know i can validate in JS, but for my particular case i want to do it solely in the makrup.

You can use regular expressions with HTML5 using the pattern attribute.

How can I validate number between 1 and 99 using regular expression? - Will give you some information about different ways to check if a number is between 1 and 99

From your example, you could use the following

<input data-bind="value : $root.rootData.Page" class="form-control" pattern="^[1-9][0-9]?$">

instead of using regex to match a number field, why not just use the number type and provide min/max?

<input type="number" min="1" max="99" step="1" data-bind="value : $root.rootData.Page" class="form-control" />

Regex could be used in combination with number type as a fallback, since FF support for the number type is lacking:

<input type="number" min="1" max="99" step="1" pattern="^[1-9][0-9]?$" data-bind="value : $root.rootData.Page" class="form-control" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM