将自定义cient-side表单验证添加到Spree前端 [英] Adding custom cient-side form validations to Spree frontend
问题描述
我试图在Spree的 checkout / address
页面的输入字段中添加一个自定义的客户端验证。
所以,这是我迄今为止所做的:
I am trying to add a custom, client-side validation to an input field in Spree's checkout/address
page.
So, here is what I have done so far:
-
将输入添加到表单中(这里使用Haml & SimpleForm):
Add the input to the form (here using Haml & SimpleForm):
= form.input :vat_number, label: Spree.t(:vat_number)
在我的 vendor / assets / javascripts / spree / frontend / checkout / address.js里面.coffee
,添加jQuery validate方法并将规则插入到 validate()
调用中:
Inside my vendor/assets/javascripts/spree/frontend/checkout/address.js.coffee
, add the jQuery validate method and insert the rule into the validate()
call:
($).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 ...
验证程序似乎没有在 vat_number
字段,尽管其余表单验证正常工作。在 javascript
调试控制台中,如果我键入 $。validator.methods
,我看到新的 vatNumber
方法,所以问题必须以我调用 validate()
的方式进行,或者与事实我使用 SimpleForm
。
The validator does not seem to operate on the vat_number
field, although the remaining form validations work. In the javascript
debug console, if I type $.validator.methods
, I do see the new vatNumber
method added in, so the problem must be either in the way I call validate()
, or something to do with the fact that I am using SimpleForm
.
我改变了 validate() / code>调用此:
I have changed the code around the validate()
call to this:
($ '#order_bill_address_attributes_vat_number').rules("add", {vatNumber: true})
($ '#checkout_form_address').validate()
在 javascript
控制台窗口中出现以下错误:
And I got the following error in the javascript
console window:
TypeError: undefined is not an object (evaluating '$.data(element.form,"validator").settings')
有没有人试图做到这一点?
Has anyone tried to do this?
推荐答案
我找出问题所在。
显然, vatNumber
方法是被添加到 address.js.coffee
文件底部的 Spree.onAddress
调用之后。
Apparently, the vatNumber
method was being added after the Spree.onAddress
call on the bottom of the address.js.coffee
file.
我将 addMethod
调用移到了另一个地方(我知道它在<$ c $中的代码之前被调用/运行c> address.js.coffee 并且它突然生效。
I moved the addMethod
call to a different place (where I know it is called/run before the code in address.js.coffee
and it suddenly worked.
现在,我想知道这是不是 CoffeeScript
的东西。代码转换为 Javascript
?
Now, I wonder if this is a CoffeeScript
thing. Could the order of the code change after the code is converted to Javascript
?
这篇关于将自定义cient-side表单验证添加到Spree前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!