Matteo Scandolo | fb46ae6 | 2017-08-08 09:10:50 -0700 | [diff] [blame] | 1 | |
| 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 Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 19 | export interface IXosFormHelpersService { |
| 20 | _getFieldFormat(value: any): string; |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 21 | } |
| 22 | |
Matteo Scandolo | a7df719 | 2017-04-11 15:37:04 -0700 | [diff] [blame] | 23 | export class XosFormHelpers implements IXosFormHelpersService { |
Matteo Scandolo | b2225a0 | 2017-04-11 15:23:04 -0700 | [diff] [blame] | 24 | static $inject = []; |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 25 | |
Matteo Scandolo | b2225a0 | 2017-04-11 15:23:04 -0700 | [diff] [blame] | 26 | public _getFieldFormat = (value) => { |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 27 | 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 Scandolo | a7df719 | 2017-04-11 15:37:04 -0700 | [diff] [blame] | 59 | |
| 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 Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 64 | } |
Matteo Scandolo | 80c3a65 | 2017-01-06 10:48:31 -0800 | [diff] [blame] | 65 | |