Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 1 | import {IXosConfigHelpersService} from '../services/helpers/config.helpers'; |
Matteo Scandolo | 80c3a65 | 2017-01-06 10:48:31 -0800 | [diff] [blame] | 2 | import {IXosFormInput} from './form'; |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 3 | |
| 4 | export interface IXosFormHelpersService { |
| 5 | _getFieldFormat(value: any): string; |
| 6 | parseModelField(fields: any): any[]; |
| 7 | buildFormStructure(modelField: any[], customField: any[], model: any, order: string[]): any; |
Matteo Scandolo | 80c3a65 | 2017-01-06 10:48:31 -0800 | [diff] [blame] | 8 | buildFormData(fields: IXosFormInput[], model: any): any; |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 9 | } |
| 10 | |
| 11 | export class XosFormHelpers { |
| 12 | static $inject = ['ConfigHelpers']; |
| 13 | |
| 14 | constructor ( |
| 15 | private ConfigHelpers: IXosConfigHelpersService |
| 16 | ) { |
| 17 | |
| 18 | } |
| 19 | |
| 20 | public _isEmail = (text) => { |
| 21 | 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,}))/; |
| 22 | return re.test(text); |
| 23 | }; |
| 24 | |
| 25 | public _getFieldFormat = (value) => { |
| 26 | if (angular.isArray(value)) { |
| 27 | return 'array'; |
| 28 | } |
| 29 | |
| 30 | // check if is date |
| 31 | if ( |
| 32 | angular.isDate(value) || |
| 33 | ( |
| 34 | !Number.isNaN(Date.parse(value)) && // Date.parse is a number |
| 35 | /^\d+-\d+-\d+\D\d+:\d+:\d+\.\d+\D/.test(value) // the format match ISO dates |
| 36 | )) { |
| 37 | return 'date'; |
| 38 | } |
| 39 | |
| 40 | // check if is boolean |
| 41 | // isNaN(false) = false, false is a number (0), true is a number (1) |
| 42 | if (typeof value === 'boolean') { |
| 43 | return 'boolean'; |
| 44 | } |
| 45 | |
| 46 | // check if a string is an email |
| 47 | if (this._isEmail(value)) { |
| 48 | return 'email'; |
| 49 | } |
| 50 | |
| 51 | // if null return string |
| 52 | if (angular.isString(value) || value === null) { |
| 53 | return 'text'; |
| 54 | } |
| 55 | |
| 56 | return typeof value; |
| 57 | }; |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 58 | } |
Matteo Scandolo | 80c3a65 | 2017-01-06 10:48:31 -0800 | [diff] [blame] | 59 | |