Created
August 24, 2012 21:12
-
-
Save vendethiel/3455665 to your computer and use it in GitHub Desktop.
Form.ls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# Example usage : | |
class EmailForm extends Form | |
fields: | |
checkbox: [] #<input checkbox> with no validator takes `checked?` as a value | |
email: (is /[a-zA-Z0-9_-]+\@[a-zA-Z0-9_-]+\.[a-zA-Z]{1,4}/) | |
subject: | |
(.length > 20) | |
(text, field) -> field.is ':visible' | |
text: (.length > 50) | |
### | |
export class Form | |
elements: [] | |
(@form) -> | |
@prepare-elements! | |
# call it directly | |
@validate! | |
prepare-elements: !-> | |
@submit = @form.find ':submit' | |
.attr {+disabled} | |
for field-name of @fields #only select key | |
field = @form.find "\#form_#field-name" | |
label = @form.find "label[for='form_#field-name']" | |
tag-name = field.prop 'tagName' | |
type = if tag-name is 'INPUT' then field.attr 'type' | |
else tag-name.to-lower-case! | |
event = switch type | |
| 'text', 'password', 'textarea' => 'keyup' | |
| 'checkbox' => 'change' | |
if typeof! @fields[field-name] is not 'Array' | |
@fields[field-name] = Array @fields[field-name] | |
field[event] @validate | |
@elements[field-name] = {field, label, type} | |
validate: !~> | |
valid = true | |
for field-name, validators of @fields | |
{type, field, label} = @elements[field-name] | |
val = switch type | |
| 'checkbox' => field.is ':checked' | |
| _ => field.val! | |
input-valid = true | |
for validator in validators | |
unless validator.call @, val, field, label, @elements | |
input-valid = false | |
break | |
else | |
input-valid = val | |
if input-valid | |
label.css 'color' 'green' | |
else | |
label.css 'color' 'red' | |
valid = false | |
@submit.attr 'disabled' not valid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment