aurelia / validation

A validation plugin for Aurelia.
MIT License
132 stars 129 forks source link

Proposal for custom validation rules #275

Closed martin5575 closed 8 years ago

martin5575 commented 8 years ago

Hi all,

I wonder, if there is a concept for custom validation rules. I.e. a callback that can be used for complex validations. Since I could not find any, I added a customRule by extending the prototype in:

import {validate} from 'validate.js'; import {ValidationRule,ValidationRules} from 'aurelia-validatejs';

// add custom-validator in basic module, i.e. validatorjs // look at https://validatejs.org/#custom-validator for details if (!validate.validators['custom']) { validate.validators.custom = function (value, options, key, attributes) { return options.rule(value) ? options.message : null; }; }

// now add a custom rule in ValidationRules factory if (!ValidationRules.prototype['customRule']) { ValidationRules.prototype.customRule = function (config) { this.addRule(this.currentProperty, new ValidationRule('custom', config)); return this; } }

// usage i like that: this.validator = ValidationRules .ensure('name') .required({message: '^Please enter name.'}) .customRule({message: '^Name is used already.', rule: this.validateName, names: this.newCustomerNames, oldName: this.oldName});

// and rule validateName(value) { if (this.oldName==value) return false; // ... check against list, ... }

Since this solution extends the prototype it is somehow a bit aweful. I wonder if customRules will be added to aurelia within the next months.

By the way, there is still a lack in this solutiuon. When I add a reference to the model within my rule. It will not serialize to json due to circular references. But I could not figure out this issue yet, since the field "undefined" of "metadate" is marked as isEnumerable=false. Does anyone have a Suggestion for that as well?

Thanks a lot in advance! Martin

EisenbergEffect commented 8 years ago

I'm closing this since we have async, custom and other use cases tracked in other issues. Thanks!