-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (56 loc) · 1.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
*
* For usage example see test/decval.js
*
*/
var validate = function(value, integrals, fractionals){
integrals = typeof integrals !== 'undefined' ? integrals : 3;
fractionals = typeof fractionals !== 'undefined' ? fractionals : 2;
if(integrals < 1 || fractionals < 1){
throw new Error('Integrals and fractionals must be at least 1');
}
var ok = true;
if(typeof value !== 'string'){
ok = false;
} else {
// if no decimal separator is found, only check the number of integrals
var onlyIntegrals = false;
var intPart;
if(value.indexOf('.') === -1){
onlyIntegrals = true;
intPart = value;
} else {
intPart = value.split('.')[0];
}
var fracPart = value.split('.')[1];
if(!intPart || (!onlyIntegrals && !fracPart)){
ok = false;
} else {
if(intPart.length > integrals || intPart.length < 1 || (!onlyIntegrals && (fracPart.length > fractionals))){
ok = false;
} else {
// integral part
var intPartNr = parseInt(intPart, 10);
// latter check for non numeric
if(intPartNr < 0 || '' + intPartNr !== intPart){
ok = false;
}
if(!onlyIntegrals){
// fractional part
for(var i = 0; i < fracPart.length; i++){
// check for non numeric
var fracPartNr = parseInt(fracPart.substring(i, i + 1), 10);
if('' + fracPartNr !== fracPart.substring(i, i + 1)){
ok = false;
break;
}
}
}
}
}
}
return ok;
};
if(typeof module !== 'undefined' && module.exports !== null){
exports.validate = validate;
}