Skip to content

Commit 01ebd5a

Browse files
committed
add validator for colors - HEX
1 parent 4c4fdd2 commit 01ebd5a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/modules/color.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* jQuery Form Validator Module: Color
3+
* ------------------------------------------
4+
* Created by dszymczuk <https://github.com/dszymczuk>
5+
*
6+
*
7+
* This form validation module adds validators for some color formats like: hex, rgb, rgba, hsl, hsla.
8+
* Also it allow to use transparent as color
9+
* This module adds the following validators:
10+
* - color
11+
*
12+
* @license MIT
13+
*/
14+
(function($) {
15+
16+
$.formUtils.registerLoadedModule('color');
17+
18+
/**
19+
* Check HEX format
20+
*/
21+
$.formUtils.addValidator({
22+
name: 'hex',
23+
validatorFunction: function(val, $el) {
24+
if ($el.valAttr('allow-transparent') === 'true' && val === 'transparent') {
25+
return true;
26+
}
27+
28+
var startWithHex = val[0] === '#';
29+
if (!startWithHex) {
30+
return false;
31+
}
32+
33+
var isCorrectLength = val.length === 4 || val.length === 7;
34+
35+
if (isCorrectLength) {
36+
var regex = /[0-9a-f]/i;
37+
var valueSliced = val.slice(1).split('');
38+
var isValid = true;
39+
valueSliced.forEach(function(i) {
40+
if (i.match(regex) === null) {
41+
isValid = false;
42+
}
43+
});
44+
return isValid;
45+
}
46+
47+
return false;
48+
},
49+
errorMessage: '',
50+
errorMessageKey: 'badHex'
51+
});
52+
53+
54+
55+
56+
})(jQuery);

0 commit comments

Comments
 (0)