UNPKG

1.89 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 a string matches a regex
21 * @private
22 * @class
23 * @memberof module:concerto-core
24 */
25class StringValidator extends Validator{
26
27 /**
28 * Create a StringValidator.
29 * @param {Field} field - the field this validator is attached to
30 * @param {Object} validator - The validation string. This must be a regex
31 * expression.
32 *
33 * @throws {IllegalModelException}
34 */
35 constructor(field, validator) {
36 super(field,validator);
37 try {
38 // discard the leading / and closing /
39 this.regex = new RegExp(validator.substring(1,validator.length-1));
40 }
41 catch(exception) {
42 this.reportError(exception.message);
43 }
44 }
45
46 /**
47 * Validate the property
48 * @param {string} identifier the identifier of the instance being validated
49 * @param {Object} value the value to validate
50 * @throws {IllegalModelException}
51 * @private
52 */
53 validate(identifier, value) {
54 if(value !== null) {
55 if(!this.regex.test(value)) {
56 this.reportError(identifier, 'Value + \'' + value + '\' failed to match validation regex: ' + this.regex);
57 }
58 }
59 }
60}
61
62module.exports = StringValidator;