我已将此方法放在一起,以便在rails应用程序中实现一些基本验证。
我对rails / coffeescript很新,并且想知道是否有人有关于重构/简化它的想法:
validateBillingAddress: (event) ->
add1 = $('#user_billing_address_1')
city = $('#user_billing_city')
zip = $('#user_billing_zip')
add1.removeClass('error')
city.removeClass('error')
zip.removeClass('error')
if !$('#user_billing_agreement').is(':checked')
$('button[type=submit]').removeAttr('disabled')
alert('You must agree to the subscription')
return
if !add1.val().length
$('button[type=submit]').removeAttr('disabled')
add1.addClass('error')
return
else if !city.val().length
$('button[type=submit]').removeAttr('disabled')
city.addClass('error')
return
else if !zip.val().length
$('button[type=submit]').removeAttr('disabled')
zip.addClass('error')
return
else
@processCard()
event.preventDefault()
答案 0 :(得分:3)
我认为您可以尝试这样的事情(未经测试)
validateBillingAddress: (event) ->
event.preventDefault()
fields = $('#user_billing_address_1, #user_billing_city, #user_billing_zip')
fields.removeClass('error')
unless $('#user_billing_agreement').is(':checked')
$('button[type=submit]').removeAttr('disabled')
alert('You must agree to the subscription')
return
fields.each ->
if !$(this).val().length
$('button[type=submit]').removeAttr('disabled')
$(this).addClass('error')
if fields.filter('.error').length > 0
return
else
@processCard()
答案 1 :(得分:1)
这是我的看法。
非常小的单一关注功能。这可能是过度的,但我发现大多数应用程序的复杂性会增加,并且提前获得一个干净的结构会有所帮助。
此外,它还为稍后在其他表单上重用此代码奠定了基础。甚至可能会做一个咖啡师课程。
#
# Handle submit event, validate, and submit
#
$('form').on "submit", ->
if isValidBillingAddress() and isAgreementChecked()
@processCard()
#
# Validation checks
#
isAgreementChecked = ->
if $('#user_billing_agreement').is(':checked')
true
else
alert('You must agree to the subscription')
false
isValidBillingAddress = ->
enableForm()
for field in requiredFormFields()
do (field) ->
if isInvalidData(field)
showErrorOnField(field)
else
field.removeClass('error')
#
# Support functions
#
requiredFormFields = ->
address1 = $("#user_billing_address_1")
city = $("#user_billing_city")
zip = $("#user_billing_zip")
[address1, city, zip]
isInvalidData = (field) ->
field.val() is ""
showErrorOnField = (field) ->
field.addClass('error')
enableForm = ->
$('button[type=submit]').removeAttr('disabled')