1 | if (typeof require !== 'undefined') {
|
2 | var Validator = require('../src/validator.js');
|
3 | var expect = require('chai').expect;
|
4 | } else {
|
5 | var Validator = window.Validator;
|
6 | var expect = window.chai.expect;
|
7 | }
|
8 |
|
9 | describe('register a custom validation rule', function() {
|
10 | it('should be able to get validation rule', function() {
|
11 | Validator.register('telephone', function(val) {
|
12 | return val.match(/^\d{3}-\d{3}-\d{4}$/);
|
13 | });
|
14 |
|
15 | var validator = new Validator();
|
16 | expect(validator.getRule('telephone').validate).to.be.a.function;
|
17 | });
|
18 |
|
19 | it('should pass the custom telephone rule registration', function() {
|
20 | Validator.register('telephone', function(val) {
|
21 | return val.match(/^\d{3}-\d{3}-\d{4}$/);
|
22 | });
|
23 |
|
24 | var validator = new Validator({
|
25 | phone: '213-454-9988'
|
26 | }, {
|
27 | phone: 'telephone'
|
28 | });
|
29 | expect(validator.passes()).to.be.true;
|
30 | });
|
31 |
|
32 | it('should override custom rules', function() {
|
33 | Validator.register('string', function(val) {
|
34 | return true;
|
35 | });
|
36 |
|
37 | var validator = new Validator({
|
38 | field: ['not a string']
|
39 | }, {
|
40 | field: 'string'
|
41 | });
|
42 |
|
43 | expect(validator.passes()).to.be.true;
|
44 | expect(validator.fails()).to.be.false;
|
45 | Validator.register('string', function(val) {
|
46 | return typeof val === 'string';
|
47 | }, 'The :attribute must be a string.');
|
48 | });
|
49 |
|
50 | it('should throw error in case of unknown validator rule', function () {
|
51 | var validator = new Validator({
|
52 | field: 'test'
|
53 | }, {
|
54 | field: 'unknown'
|
55 | });
|
56 |
|
57 | expect(validator.passes).to.throw();
|
58 | expect(validator.fails).to.throw();
|
59 | });
|
60 |
|
61 | it('should allow to add custom validator to unknown validator rules', function () {
|
62 | Validator.registerMissedRuleValidator(function() {
|
63 | return true;
|
64 | });
|
65 |
|
66 | var validator = new Validator({
|
67 | field: 'test'
|
68 | }, {
|
69 | field: 'unknown'
|
70 | });
|
71 |
|
72 | expect(validator.passes()).to.be.true;
|
73 | expect(validator.fails()).to.be.false;
|
74 | });
|
75 | });
|