Skip to content

Instantly share code, notes, and snippets.

@itzaks
Created April 22, 2014 14:38
Show Gist options
  • Select an option

  • Save itzaks/11181698 to your computer and use it in GitHub Desktop.

Select an option

Save itzaks/11181698 to your computer and use it in GitHub Desktop.
VALIDATIONS =
mobile_number: (val) -> val.match /[06]{1}[7]{1}[0-9]{8}/
zipcode: (val) -> val.match /^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$/
email: (val) -> val.match /^\S+@\S+\.\S+$/
personnummer: (val) ->
console.log (val.match /[1-2][0|9][0-9]{2}[0-1][0-9][0-3][0-9][0-9]{4}/), val.length is 12
(val.match /[1-2][0|9][0-9]{2}[0-1][0-9][0-3][0-9][0-9]{4}/) and val.length is 12
module.exports = ($form, validation) ->
$fields = $form.find("input, textarea").removeClass("is-error")
errorfields = []
for field, valid_check of validation
#which inputs should be validated by valid_check
$inputs = $fields.filter(field)
continue unless $inputs.length
is_valid = switch typeof(valid_check).toLowerCase()
when "string" then VALIDATIONS[valid_check] or -> true
else valid_check
#validate each input with attached validation
errorfields.push(el) for el in $inputs when not is_valid $(el).val()
$(errorfields).addClass "is-error"
return errorfields.length is 0
@itzaks
Copy link
Author

itzaks commented Apr 22, 2014

Example usage:

form_submit: (event) ->
  return validate $(event.currentTarget),
    '[name="person[person_number]"]': 'personnummer'
    '[name="person[email]"]': 'email'
    '[name="person[mobile_number]"]': 'mobile_number'

@itzaks
Copy link
Author

itzaks commented Apr 22, 2014

Example error styles:

.form-input
  border: 1px solid #CCC
.form-input.is-error
  border-color: #F15344 !important
  box-shadow: 0 0 10px rgba(255, 0, 0, 0.08)

.form-error //error msg
  color: #F15344
  display: none
.form-input.is-error + .form-error
  display: block

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment