Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First draft of validation binding for chip #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ module.exports = function(grunt) {
'src/filter.coffee',
'src/bindings.coffee',
'src/filters.coffee',
'src/diff.coffee'
'src/diff.coffee',
'src/validation.coffee'
];

var libFiles = [
Expand Down
104 changes: 104 additions & 0 deletions dist/chip.js
Original file line number Diff line number Diff line change
Expand Up @@ -3416,4 +3416,108 @@ if (!Date.prototype.toISOString) {

chip.diff = diff;

chip.binding('bind-validation', function(element, attr, controller) {
controller[attr.value] = {};
return controller.validationGroup = attr.value;
});

chip.binding('validate-*', function(element, attr, controller) {
var opt, optArry, optionKey, optionValMsg, options, optsArry, type, validateField, validations, _i, _len, _ref;
validations = app.rootController.validations != null;
if (!validations) {
return console.warn('No validation rules found.');
} else {
type = attr.camel;
if (attr.value === '') {
options = {};
options["default"] = true;
} else {
if (attr.value.indexOf(':') < 1) {
options = controller["eval"](attr.value);
if (typeof options !== 'object') {
options = {};
options[attr.value] = true;
}
} else {
options = {};
optsArry = attr.value.split('|');
for (_i = 0, _len = optsArry.length; _i < _len; _i++) {
opt = optsArry[_i];
optArry = opt.split(':');
optionKey = optArry[0].trim();
optionValMsg = optArry[1].split('-e');
options[optionKey] = {};
options[optionKey].value = optionValMsg[0].trim();
options[optionKey].errorMessage = (_ref = optionValMsg[1]) != null ? _ref.trim() : void 0;
}
}
}
element.on('change', function() {
var validResponse, value;
value = element.val();
validResponse = validateField(value, type, options);
if (validResponse.valid) {
element.removeClass('chip_validation_invalid');
element.addClass('chip_validation_valid');
} else {
console.error(validResponse.errorMsgs);
element.removeClass('chip_validation_valid');
element.addClass('chip_validation_invalid');
}
if (!controller[controller.validationGroup][element.attr('name')]) {
controller[controller.validationGroup][element.attr('name')] = {};
}
return controller[controller.validationGroup][element.attr('name')] = validResponse;
});
return validateField = function(value, type, options) {
var errorMsgs, isValid, optionName, optionValue, response, rule, validateMsg, validateVal, validation, _ref1, _ref2;
response = {
valid: true,
message: '',
errorMsgs: []
};
validateVal = function(validation) {
if (validation.value != null) {
return validation.value;
} else {
return validation;
}
};
validateMsg = function(validation) {
if (validation.message != null) {
return validation.message;
} else {
return null;
}
};
isValid = true;
errorMsgs = [];
for (optionName in options) {
optionValue = options[optionName];
validation = ((_ref1 = validations[type]) != null ? _ref1[optionName] : void 0) || ((_ref2 = validations.all) != null ? _ref2[optionName] : void 0);
if (validation != null) {
rule = validation.evaluation.replace('{x}', '"' + value + '"').replace('{y}', optionValue.value);
if (eval(rule)) {
isValid = true;
} else {
isValid = false;
if (validation.errorMessage) {
errorMsgs.push(validation.errorMessage.replace('{y}', optionValue.value));
} else {
validation.errorMessage('Input for this field is invalid.');
}
}
} else {
'validation missing';
response.valid = true;
console.warn('Validation method: ' + optionName + ' not found!');
}
}
response.valid = isValid;
response.errorMsgs = errorMsgs;
return response;
};
}
});

}).call(this);
4 changes: 2 additions & 2 deletions dist/chip.min.js

Large diffs are not rendered by default.

136 changes: 136 additions & 0 deletions src/validation.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# ## bind-validation
chip.binding 'bind-validation', (element, attr, controller) ->
controller[attr.value] = {}
controller.validationGroup = attr.value

# ## validate-*
chip.binding 'validate-*', (element,attr,controller) ->
# When defining a validation rule, use the following:
# {x} = field value, {y} = validation option value

## Example
# validations =
# all:
# required:
# evaluation: '{x} != ""'
# errorMessage: 'This is a required field.'
# text:
# minLength:
# evaluation: '{x}.length >= {y}'
# errorMessage: 'This field must be at least {y} characters long.'
# maxLength:
# evaluation: '{x}.length <= {y}'
# errorMessage: 'This field must be at most {y} characters long.'
# number:
# minValue:
# evaluation: '{x} >= {y}'
# errorMessage: 'This value must be greater than {y}.'
# maxValue:
# evaluation: '{x} <= {y}'
# errorMessage: 'This value must be less than {y}.'
# email:
# default:
# evaluation: '{y}.match(/@/)'
# errorMessage: 'Please enter a valid email address.'

validations = app.rootController.validations?
if !validations
console.warn 'No validation rules found.'
else
type = attr.camel
# Initially tested for a validation object with typeof, but that felt too
# rigid, so I simplfied it a bit.

if attr.value is ''
options = {}
options.default = true
else
if attr.value.indexOf(':') < 1
# Loading options as an object passed from the controller
options = controller.eval(attr.value)
unless typeof options is 'object'
options = {}
options[attr.value] = true
else
# Attempt to parse options directly from validation attribute
# We will probably need to spend more time working out the best format here
# since passing an object string in the attribute isn't going to work.
#
# Currently using the following 'shortcode' for validation options:
# option:value -e 'This is an optional message'
#
# Seperate options with | character (do not love this).
options = {}
optsArry = attr.value.split '|'
for opt in optsArry
optArry = opt.split ':'
optionKey = optArry[0].trim()
optionValMsg = optArry[1].split '-e'
options[optionKey] = {}
options[optionKey].value = optionValMsg[0].trim()
options[optionKey].errorMessage = optionValMsg[1]?.trim()

element.on 'change', ->
value = element.val()
validResponse = validateField(value,type,options)
if validResponse.valid
# Do some happy, positive things
element.removeClass('chip_validation_invalid')
element.addClass('chip_validation_valid')
else
# Scorch the earth with shameful red error messages
console.error validResponse.errorMsgs
element.removeClass('chip_validation_valid')
element.addClass('chip_validation_invalid')
# In addition to adding / removing CSS classes to elements being validated,
# a validation object is added to the `validationController` under the
# named `validationGroup` by the element name.
# (will only work with simple field names)
unless controller[controller.validationGroup][element.attr('name')]
controller[controller.validationGroup][element.attr('name')] = {}
controller[controller.validationGroup][element.attr('name')] =
validResponse

validateField = (value,type,options) ->
response = {
valid:true
message:''
errorMsgs:[]
}

validateVal = (validation) ->
if validation.value?
return validation.value
else
return validation

validateMsg = (validation) ->
if validation.message?
return validation.message
else
return null

isValid = true
errorMsgs = []
for optionName, optionValue of options
validation = validations[type]?[optionName] ||
validations.all?[optionName]
if validation?
rule = validation.evaluation.replace('{x}','"' + value + '"')
.replace('{y}',optionValue.value)
if eval rule
isValid = true;
else
isValid = false
if validation.errorMessage
errorMsgs.push validation.errorMessage.replace '{y}',
optionValue.value
else
validation.errorMessage 'Input for this field is invalid.'
else
'validation missing'
response.valid = true;
console.warn 'Validation method: ' + optionName + ' not found!'
response.valid = isValid
response.errorMsgs = errorMsgs
return response