
產(chǎn)品中需要針對(duì)物品設(shè)置價(jià)格,按照要求最低值是0.99元,控件上下箭頭步進(jìn)1元。
剛好 html5 中針對(duì) number 類(lèi)型的 input 新增了 min 和 step 兩個(gè)屬性,顧名思義一個(gè)是最小值另一個(gè)是步進(jìn)值。按要求設(shè)置好后很順利實(shí)現(xiàn)目標(biāo)。
直到提交表單時(shí),發(fā)現(xiàn)如果不是0.99結(jié)尾的整數(shù)都會(huì)被提示非法值,在網(wǎng)上搜了下看到幾個(gè)例子和我司產(chǎn)品一樣使用 bootstrap 架構(gòu),min 和 step 用法也相同,只是多了幾個(gè)自定義的屬性。當(dāng)時(shí)自作聰明以為問(wèn)題出在多出來(lái)的自定義屬性上,調(diào)查了很久發(fā)現(xiàn)網(wǎng)上的例子應(yīng)該加載了其他的 js 控件做了輔助驗(yàn)證,和我的問(wèn)題并沒(méi)有半毛錢(qián)的關(guān)系。直到查到 w3c 標(biāo)準(zhǔn)的定義,發(fā)現(xiàn) step 并不只是控制控件的步進(jìn)值,對(duì)最終的值也會(huì)產(chǎn)生約束。
Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.
此為具體校驗(yàn)規(guī)則,其中 step base 求值規(guī)則摘要如下
The step base is the value returned by the following algorithm:
- If the element has a min content attribute, and the result of applying the algorithm to convert a string to a number to the value of the min content attribute is not an error, then return that result and abort these steps.
所以我定義了 min="0.99" step="1" 之后,校驗(yàn)規(guī)則就變成除以 step 取余然后減去 min 為 0 。
Otherwise, if the attribute's value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.
參考 step 的說(shuō)明,定義成 step="any" 就可以繞過(guò) step 的檢查,而且貌似默認(rèn)的步進(jìn)就是 1,成功達(dá)到目的。