File size: 12,266 Bytes
e09caf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
jQuery.fn.validate = function ()
{
    /* Mensajes por defecto */
    var _mensaje = {
        campo_obligatorio: 'Este campo es obligatorio',
        campo_numerico: 'Este campo no es numérico',
        campo_correo: 'Este campo no es un correo',
        campo_longitud: 'Este campo debe tener una longitud de {0} caracteres',
        campo_min: 'Este campo debe tener como mínimo {0} caracteres',
        campo_max: 'Este campo debe tener como máximo {0} caracteres',
        campo_valido: 'Este campo no es válido',
        campo_ip: 'Este campo no es una IP válida',
        campo_url: 'Este campo no es una URL válida',
        campo_social_twitter: 'Este campo no es una URL válida de Twitter',
        campo_social_facebook: 'Este campo no es una URL válida de Facebook',
        campo_social_youtube: 'Este campo no es una URL válida de Youtube'
    };

    var form = $(this);

    try {
        /* Cuenta los posibles errores encontrados */
        var errores = 0;

        /* Los controles encontrados por nuestra Clase de CSS */
        var controles = $('[data-validacion-tipo]', form);

        /* Comenzamos a validar cada control */
        $.each(controles, function () {

            /* El control actual del arreglo */
            var obj = $(this);

            /* No nos interesa validar controles con el estado readonly/disabled */
            if (!obj.prop('readonly') || !obj.prop('disabled'))
            {
                if ($(this).data('validacion-tipo') != undefined) {
                    /* El tipo de validacion asignado a este control */
                    $.each($(this).data('validacion-tipo').split('|'), function (i, v) {

                        /* El control donde vamos agregar el texto */
                        var small = $('<small />');

                        /* El contenedor del control */
                        var form_group = obj.closest('.form-group');
                        form_group.removeClass('has-error'); /* Limpiamos el estado de error */

                        /* Capturamos el label donde queremos mostrar el mensaje */
                        var label = form_group.find('label');
                        label.find('small').remove(); /* Eliminamos el mensaje anterior */
                        label.append(small);

                        /* Validamos si es requerido */
                        if (v == 'requerido') {
                            if (obj.val().length == 0) {

                                /* Contamos que hay un error */
                                errores++;

                                /* Agregamos la clase de bootstrap de errores */
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_obligatorio);
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Validamos si es numérico */
                        if (v == 'numero') {
                            if (!obj.val().match(/^([0-9])*[.]?[0-9]*$/) && obj.val().length > 0) {

                                errores++;
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_numerico);
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Validamos si es un email */
                        if (v == 'email') {
                            if (!obj.val().match(/^[0-9a-z_\-\.]+@[0-9a-z\-\.]+\.[a-z]{2,4}$/i) && obj.val().length > 0) {

                                errores++;
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_correo);
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Longitud de caracteres a tener */
                        if (v.indexOf('longitud') > -1 && obj.val().length > 0) {

                            // Necesitamos saber la longitud máxima
                            var _longitud = v.split(':');
                            if (obj.val().length != _longitud[1]) {

                                errores++;
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_longitud.replace('{0}', _longitud[1]));
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Cantidad minima de caracteres */
                        if (v.indexOf('min') > -1 && obj.val().length > 0) {

                            // Necesitamos saber la longitud máxima
                            var _min = v.split(':');
                            if (obj.val().length < _min[1]) {

                                errores++;
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_min.replace('{0}', _min[1]));
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Cantidad maxima de caracteres */
                        if (v.indexOf('max') > -1 && obj.val().length > 0) {

                            // Necesitamos saber la longitud máxima
                            var _min = v.split(':');
                            if (obj.val().length > _min[1]) {

                                errores++;
                                form_group.addClass('has-error');

                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_max.replace('{0}', _min[1]));
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Validación mediante una funcion personalizada */
                        if (v.indexOf('funcion') > -1 && obj.val().length > 0) {

                            // Necesitamos saber la longitud máxima
                            var _funcion = v.split(':');

                            // Respuesta de la funcion
                            var _respuesta = false;

                            // Espera parámetros
                            if (_funcion.length >= 3) {
                                _respuesta = window[_funcion[1]].apply(this, _funcion[2].split(','));
                            } else {
                                _respuesta = window[_funcion[1]]();
                            }

                            /* Mostramos el mensaje */
                            if (!_respuesta || _respuesta == undefined) {

                                errores++;
                                form_group.addClass('has-error');

                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_valido);
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false;
                            }
                        }

                        /* Válidamos una IP */
                        if (v == 'ip') {
                            if (!obj.val().match(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/) && obj.val().length > 0) {

                                errores++;
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_ip);
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Válidamos una URL válida */
                        if (v == 'url') {
                            if (!obj.val().match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/) && obj.val().length > 0) {

                                errores++;
                                form_group.addClass('has-error');

                                /* Mostramos el mensaje */
                                if (obj.data('validacion-mensaje') == undefined) {
                                    small.text(_mensaje.campo_url);
                                } else {
                                    small.text(obj.data('validacion-mensaje'));
                                }

                                return false; /* Rompe el bucle */
                            }
                        }

                        /* Comparamos con otro control */
                        if (v.indexOf('compara') > -1 && obj.val().length > 0) {
                            var _comparacion = true;
                            var _aComparar = v.split(':');

                            $(_aComparar[1], form).each(function () {
                                if (obj.val() != $(this).val()) {

                                    errores++;
                                    form_group.addClass('has-error');

                                    if (obj.data('validacion-mensaje') == undefined) {
                                        small.text(_mensaje.campo_valido);
                                    } else {
                                        small.text(obj.data('validacion-mensaje'));
                                    }
                                }
                            })
                        }

                    })
                }                
            }
        })

        /* Verificamos si ha sido validado */
        return (errores == 0);
    } catch (e) {
        console.error(e);
        return false;
    }
}