blob: bbad2c82d52562bdd2e83ff2ed858353cbef999b [file] [log] [blame]
Matteo Scandolo80c3a652017-01-06 10:48:31 -08001import {IXosFormInput} from './form';
Matteo Scandoloee655a12016-12-19 15:38:43 -08002
3export interface IXosFormHelpersService {
4 _getFieldFormat(value: any): string;
5 parseModelField(fields: any): any[];
6 buildFormStructure(modelField: any[], customField: any[], model: any, order: string[]): any;
Matteo Scandolo80c3a652017-01-06 10:48:31 -08007 buildFormData(fields: IXosFormInput[], model: any): any;
Matteo Scandoloee655a12016-12-19 15:38:43 -08008}
9
10export class XosFormHelpers {
Matteo Scandolob2225a02017-04-11 15:23:04 -070011 static $inject = [];
Matteo Scandoloee655a12016-12-19 15:38:43 -080012
13 public _isEmail = (text) => {
14 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,}))/;
15 return re.test(text);
16 };
17
Matteo Scandolob2225a02017-04-11 15:23:04 -070018 public _getFieldFormat = (value) => {
Matteo Scandoloee655a12016-12-19 15:38:43 -080019 if (angular.isArray(value)) {
20 return 'array';
21 }
22
23 // check if is date
24 if (
25 angular.isDate(value) ||
26 (
27 !Number.isNaN(Date.parse(value)) && // Date.parse is a number
28 /^\d+-\d+-\d+\D\d+:\d+:\d+\.\d+\D/.test(value) // the format match ISO dates
29 )) {
30 return 'date';
31 }
32
33 // check if is boolean
34 // isNaN(false) = false, false is a number (0), true is a number (1)
35 if (typeof value === 'boolean') {
36 return 'boolean';
37 }
38
39 // check if a string is an email
40 if (this._isEmail(value)) {
41 return 'email';
42 }
43
44 // if null return string
45 if (angular.isString(value) || value === null) {
46 return 'text';
47 }
48
49 return typeof value;
50 };
Matteo Scandoloee655a12016-12-19 15:38:43 -080051}
Matteo Scandolo80c3a652017-01-06 10:48:31 -080052