Skip to content

Instantly share code, notes, and snippets.

@yuchant
Created May 15, 2014 23:39
Show Gist options
  • Save yuchant/955414c26733adfc1e25 to your computer and use it in GitHub Desktop.
Save yuchant/955414c26733adfc1e25 to your computer and use it in GitHub Desktop.
# custom validation logic
$.validator.addMethod 'validateShipState', (value, element) ->
# if the element contains an arbitrary piece of data called `custom-validator-exception`, don't allow form to validate.
if $(element).data('custom-validator-exception')
return false
return true
, ->
return $("[name=s_state]").data('custom-validator-exception')
$shipForm = $(".form-shipping-step")
validator = $shipForm.validate
rules:
s_state:
required: true
validateShipState: true
# the event handlers setting the invalidation logic:
$("[name=s_country], [name=s_state]").on 'change', (ev) =>
$this = $ ev.currentTarget
$state.data('custom-validator-exception', 'Currently validating') # this should never appear as nothing calls valid()
$.ajax
url: ''
dataType: 'json'
method: 'post'
headers:
X_AJAX_HANDLER: 'set_tax'
data:
country: $country.val()
state: $state.val()
success: (response) =>
@updateTotals(response.cart)
$state.data('custom-validator-exception', false)
$state.valid()
error: (xhr) =>
response = $.parseJSON xhr.responseText
# set custom validator exception value.. prevent this form from proceeding.
$state.data('custom-validator-exception', response.message)
$state.valid()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment