UNPKG

2.86 kBJavaScriptView Raw
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14
15'use strict';
16
17const Validator = require('./validator');
18
19/**
20 * A Validator to enforce that non null numeric values are between two values.
21 * @private
22 * @class
23 * @memberof module:concerto-core
24 */
25class NumberValidator extends Validator{
26
27 /**
28 * Create a NumberValidator.
29 * @param {Field} field - the field this validator is attached to
30 * @param {Object} ast - The ast for the range defined as [lower,upper] (inclusive).
31 *
32 * @throws {IllegalModelException}
33 */
34 constructor(field, ast) {
35 super(field, ast);
36
37 this.lowerBound = null;
38 this.upperBound = null;
39
40 if(ast.lower) {
41 this.lowerBound = parseFloat(ast.lower);
42 }
43
44 if(ast.upper) {
45 this.upperBound = parseFloat(ast.upper);
46 }
47
48 if(this.lowerBound === null && this.upperBound === null) {
49 // can't specify no upper and lower value
50 this.reportError(null, 'Invalid range, lower and-or upper bound must be specified.');
51 } else if (this.lowerBound === null || this.upperBound === null) {
52 // this is fine and means that we don't need to check whether upper > lower
53 } else {
54 if(this.lowerBound > this.upperBound) {
55 this.reportError(null, 'Lower bound must be less than or equal to upper bound.');
56 }
57 }
58 }
59
60 /**
61 * Validate the property
62 * @param {string} identifier the identifier of the instance being validated
63 * @param {Object} value the value to validate
64 * @throws {IllegalModelException}
65 * @private
66 */
67 validate(identifier, value) {
68 if(value !== null) {
69 if(this.lowerBound !== null && value < this.lowerBound) {
70 this.reportError(identifier, 'Value is outside lower bound ' + value);
71 }
72
73 if(this.upperBound !== null && value > this.upperBound) {
74 this.reportError(identifier, 'Value is outside upper bound ' + value);
75 }
76 }
77 }
78
79 /**
80 * Returns a string representation
81 * @return {string} the string representation
82 * @private
83 */
84 toString() {
85 return 'NumberValidator lower: ' + this.lowerBound + ' upper: ' + this.upperBound;
86 }
87}
88
89module.exports = NumberValidator;