向Spree前端添加自定义的客户端表单validation
我正在尝试在Spree的checkout/address
页面的输入字段中添加自定义的客户端validation。 所以,这是我到目前为止所做的:
-
将输入添加到表单(这里使用Haml和SimpleForm):
= form.input :vat_number, label: Spree.t(:vat_number)
-
在我的
vendor/assets/javascripts/spree/frontend/checkout/address.js.coffee
,添加jQuery validate方法并将规则插入validate()
调用:($).validator.addMethod "vatNumber", (value, element) -> return false , "Something wrong!" Spree.onAddress = () -> if ($ '#checkout_form_address').is('*') ($ '#checkout_form_address').validate({ rules: { order_bill_address_attributes_vat_number: { vatNumber: true } } }) # ... rest of the file ...
尽管其余的表单validation有效,但validation器似乎不在vat_number
字段上运行。 在javascript
调试控制台中,如果我输入$.validator.methods
vatNumber
,我确实看到添加了新的vatNumber
方法,所以问题必须是我调用validate()
,或者与我的事实有关使用SimpleForm
。
我已经将validate()
调用的代码更改为:
($ '#order_bill_address_attributes_vat_number').rules("add", {vatNumber: true}) ($ '#checkout_form_address').validate()
我在javascript
控制台窗口中收到以下错误:
TypeError: undefined is not an object (evaluating '$.data(element.form,"validator").settings')
有没有人试过这样做?
我弄清楚问题是什么。
显然,在address.js.coffee
文件底部的Spree.onAddress
调用之后添加了vatNumber
方法。
我将addMethod
调用移动到另一个地方(我知道它在address.js.coffee
的代码之前被调用/运行,它突然起作用了。
现在,我想知道这是否是CoffeeScript
事情。 代码转换为Javascript
后,代码的顺序是否会发生变化?