2013-11-02 43 views
0

我已經將這種方法放在一起,以在rails應用程序中實現一些基本驗證。重構咖啡腳本方法

我很新的鐵軌/ CoffeeScript中,並想知道如果任何人有想法重構/簡化IT:

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() 

回答

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() 
+0

很好,它開箱即用。 '除非'是一個很棒的功能。也是'過濾器'一個jquery或coffeescript函數? – tmartin314

+0

'filter'是一個jQuery函數:http://api.jquery.com/filter/ –

+0

此外,如果您只需要檢查字段是否爲空,則可以使用HTML5驗證。 http://www.the-art-of-web.com/html/html5-form-validation/ – hedgesky

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')