blob: 149b3c7cf8102c807cc7da004ed8ebc8db39a581 [file] [log] [blame]
Matteo Scandolofb46ae62017-08-08 09:10:50 -07001
2/*
3 * Copyright 2017-present Open Networking Foundation
4
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8
9 * http://www.apache.org/licenses/LICENSE-2.0
10
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18
Matteo Scandoloee655a12016-12-19 15:38:43 -080019export interface IXosFormHelpersService {
20 _getFieldFormat(value: any): string;
Matteo Scandoloee655a12016-12-19 15:38:43 -080021}
22
Matteo Scandoloa7df7192017-04-11 15:37:04 -070023export class XosFormHelpers implements IXosFormHelpersService {
Matteo Scandolob2225a02017-04-11 15:23:04 -070024 static $inject = [];
Matteo Scandoloee655a12016-12-19 15:38:43 -080025
Matteo Scandolob2225a02017-04-11 15:23:04 -070026 public _getFieldFormat = (value) => {
Matteo Scandoloee655a12016-12-19 15:38:43 -080027 if (angular.isArray(value)) {
28 return 'array';
29 }
30
31 // check if is date
32 if (
33 angular.isDate(value) ||
34 (
35 !Number.isNaN(Date.parse(value)) && // Date.parse is a number
36 /^\d+-\d+-\d+\D\d+:\d+:\d+\.\d+\D/.test(value) // the format match ISO dates
37 )) {
38 return 'date';
39 }
40
41 // check if is boolean
42 // isNaN(false) = false, false is a number (0), true is a number (1)
43 if (typeof value === 'boolean') {
44 return 'boolean';
45 }
46
47 // check if a string is an email
48 if (this._isEmail(value)) {
49 return 'email';
50 }
51
52 // if null return string
53 if (angular.isString(value) || value === null) {
54 return 'text';
55 }
56
57 return typeof value;
58 };
Matteo Scandoloa7df7192017-04-11 15:37:04 -070059
60 private _isEmail = (text) => {
61 const re = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
62 return re.test(text);
63 };
Matteo Scandoloee655a12016-12-19 15:38:43 -080064}
Matteo Scandolo80c3a652017-01-06 10:48:31 -080065