PageSourceSearch

https://sede.melilla.es/sta/pages/webapps/js/uiBasicValidation.js?ver=2605.0.3

js melilla.es collected 2026-10-01 10:44:34 UTC 29,685 bytes, 873 lines download raw bytes

1var activeSubForm = 0;
2
3function configureValidations() {
4
5	// fix date validation for chrome
6	
7    jQuery.extend(jQuery.validator.methods, {
8        date: function (value, element) {
9            if (value)
10            {
11                try
12                {
13                	jQuery.datepicker.parseDate('dd/mm/yy', value);
14                }
15                catch (ex)
16                {
17                    return false;
18                }
19            }
20            return true;
21        	/*
22        	var isChrome = window.chrome;
23            // make correction for chrome
24            if (isChrome) {
25            	var validDate = /^(\d{2})\/(\d{2})\/(\d{4})?$/;    
26                return this.optional(element) || validDate.test(value);
27            }
28            // leave default behavior
29            else {
30                return this.optional(element) || 
31                !/Invalid|NaN/.test(new Date(value));
32            }
33            */
34        }
35    }); 	
36	
37    // Mensajes por defercto SIN traducción
38    // ------------------------------------
39    // Estos literales son sobreescritos por los literales definidos en CFG_APP como VALTXT_xxxxx de forma automatica
40    // mediante un fichero de recursos creado dinamicamente al arrancar la STA, que contiene la funcion: translateLiterals.
41    
42	jQuery.extend(jQuery.validator.messages, {
43	    required: "Campo obligatorio",
44	    remote: "Please fix this field.",
45	    email: "El formato del mail no es válido",
46	    url: "Por favor introduzca una url válida",
47	    date: "Por favor introduzca una fecha válida",
48	    dateISO: "Please enter a valid date (ISO).",
49	    number: "Por favor introduzca un numero correcto.",
50	    currency: "Formato incorrecto. Ejemplo: 100.00",
51	    digits: "Please enter only digits.",
52	    creditcard: "Please enter a valid credit card number.",
53	    equalTo: "Please enter the same value again.",
54	    accept: "Please enter a value with a valid extension.",
55	    maxlength: jQuery.validator.format("No se admiten más de {0} caracteres"),
56	    minlength: jQuery.validator.format("Introduzca al menos {0} caracteres"),
57	    rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
58	    range: jQuery.validator.format("Please enter a value between {0} and {1}."),
59	    max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
60	    min: jQuery.validator.format("Please enter a value greater than or equal to {0}."),
61	    checkRequired: "Debe leer y aceptar las condiciones de uso.",
62	    adr_required: "El campo de la dirección es obligatorio.",
63	    upload: "No ha adjuntado ningún documento",
64	    base_inside: jQuery.validator.format("La base imponible calculada debe estar entre {0} y {1}."),
65	    base_outside: "La base imponible calculada no puede sobrepasar {0}."
66	    	
67	});
68	
69	// A continuación se definen los METODOS creados para la STA
70	// los parametros son el nombre del metodo, la funcion de validación y el literal del error
71	// los: addClassRules siven para asociar una clase a una validación y de paso poder especificar las expresiones regulares si se requiere.
72	// jQuery.validator.methods.XXXXX se usa para definir la funcion de validación de un metodo existente
73	// --------------------------------------------------------------------------------------------------
74	
75	jQuery.validator.addMethod(
76		    "phone",
77		    function(value, element, regexp) {
78		        var check = false;
79		        return this.optional(element) || regexp.test(value);
80		    },
81		    "El teléfono no es válido."
82		);
83	
84	
85	jQuery.validator.methods.email = function( value, element ) {
86  		return this.optional( element ) || /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test( value );
87	}		
88	
89	jQuery.validator.addClassRules("phone", {
90		phone : /^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d$/
91		});	
92	
93	jQuery.validator.addMethod(
94		    "numeric",
95		    function(value, element, regexp) {
96		        var check = false;
97		        return this.optional(element) || regexp.test(value);
98		    },
99		    "Sólo se admiten números."
100		);
101	
102	jQuery.validator.addMethod("soloLetras", function (value, element) {
103
104	    if (this.optional(element)) return true;
105
106	    // ❌ 1. Detectar '
107	    if (/'/i.test(value)) return false;
108
109	    // ❌ 2. Detectar caracteres no permitidos
110	    if (/[^a-zA-Z\s']/.test(value)) return false;
111
112	    // ❌ 3. Detectar múltiples espacios
113	    if (/\s{2,}/.test(value)) return false;
114
115	    // ❌ 4. Detectar múltiples apostrofes
116	    if (/'{2,}/.test(value)) return false;
117
118	    // ❌ 5. Detectar espacios inicio/fin
119	    if (/^\s+|\s+$/.test(value)) return false;
120
121	    // ❌ 6. Detectar ' al inicio o final
122	    if (/^'+|'+$/.test(value)) return false;
123
124	    return true;
125
126	}, "Formato inválido: solo letras sin acentos y apóstrofes ('). Evite espacios o símbolos incorrectos.");
127		
128	jQuery.validator.addClassRules("solo-letras", {
129	    soloLetras: true
130	});
131		
132	// Esta entrada deberia ser anulada ja que digits ya hace esto
133	jQuery.validator.addClassRules("numeric", {
134		numeric : /^[\d]+$/
135		});	
136	
137	jQuery.validator.methods.range = function (value, element, param) {
138	    var globalizedValue = value.replaceAll(".","").replace(",", ".");
139	    return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
140	}
141	jQuery.validator.methods.max = function (value, element, param) {
142	    var globalizedValue = value.replaceAll(".","").replace(",", ".");
143	    return this.optional( element ) || globalizedValue <= param;
144	}	
145	
146	jQuery.validator.methods.number = function (value, element) {
147	    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value); 
148	}
149	
150	jQuery.validator.addMethod(
151		    "currency",
152		    function(value, element, regexp) {
153		        var check = false;
154		        return this.optional(element) || regexp.test(value);
155		    }
156		    ,"Formato incorrecto. Ejemplo: 1.200,00"		    
157		);
158	
159	jQuery.validator.addClassRules("currency", {
160		currency :  /^\s*-?((\d{1,3}(\.(\d){3})*)|\d*)(,\d{1,2})?\s?(\u20AC)?\s*$/ 
161		//currency : /^(\d+)(\,\d{1,2})?$/
162		});	
163	
164	jQuery.validator.addMethod(
165		    "checkRequired",
166		    function(value, element) {
167		        //var check = false;
168		        //return this.optional(element) || regexp.test(value);
169		    	console.log('check if checkbox is checked');
170		        return jQuery(element).is(':checked');		        
171		    }
172		);	
173	
174	
175	jQuery.validator.addMethod("subFormRequired",
176			function(value, element)
177			{
178				alert('appling subForm validation');
179				//var jQueryelement = jQuery(element);
180				if ((element).parents(".sub-form-" + activeSubForm).length)
181				{
182					return !this.optional(element);
183				}
184				return "dependency-mismatch";
185			},
186			jQuery.validator.messages.required);
187	
188	
189	jQuery.validator.addMethod(
190		    "maxDate",
191		    function(value, element, params) {
192		    	var dateMax = jQuery.datepicker.parseDate('dd/mm/yy',params);
193		    	var dateEntered = jQuery.datepicker.parseDate('dd/mm/yy',value);
194		    	return dateEntered <= dateMax;
195		    }
196		);
197	jQuery.validator.addMethod(
198		    "maxDateToday",
199		    function(value, element, params) {
200		    	var dateEntered = jQuery.datepicker.parseDate('dd/mm/yy',value);
201		    	return dateEntered <= new Date();
202		    }
203		);
204	jQuery.validator.addMethod(
205		    "minDate",
206		    function(value, element, params) {
207		    	var dateMin = jQuery.datepicker.parseDate('dd/mm/yy',params);
208		    	var dateEntered = jQuery.datepicker.parseDate('dd/mm/yy',value);
209		    	return dateEntered >= dateMin;
210		    }
211		);
212	jQuery.validator.addMethod(
213		    "minDateToday",
214		    function(value, element, params) {
215		    	var dateEntered = jQuery.datepicker.parseDate('dd/mm/yy',value);
216		    	return dateEntered >= new Date();
217		    }
218		);
219
220	jQuery.validator.addMethod(
221		    "notario",
222		    function(value, element) {
223		        return jQuery('#notario-dboid').val()!='';
224		    }
225		);
226	
227	jQuery.validator.addMethod(
228		    "epigrafe",
229		    function(value, element) {
230		        return jQuery('#epigrafe-dboid').val()!='';
231		    }
232		);
233	
234	jQuery.validator.addMethod(
235		    "upload",
236		    function(value, element) {
237		    	return jQuery(element).closest('.widget-upload-files').find('.file-uploaded-item').length  != 0;
238		    }
239		);
240	//jQuery.validator.addClassRules("upload", { upload: true});		
241
242	
243	jQuery.validator.addMethod(
244		    "adr_required",
245		    function(value, element) {
246		    	console.log('direccion: validando dirección');
247		    	if (jQuery('#'+ jQuery(element).prop('id') + '_ID').length > 0)
248		    		return jQuery('#'+ jQuery(element).prop('id') + '_ID').val() != '';
249		    	else if (jQuery(element).is(':hidden') )
250		    		return jQuery(element).val() != '-1';
251		    	else 
252		    		return jQuery(element).val() != '';
253		    }
254		);
255	jQuery.validator.addMethod(
256		    "base_inside",
257		    function(value, element) {
258		    	return jQuery(element).closest('.liqsec-param-concepto-form').data('base-inside') != 'out';
259		    },
260		    function (params, element) {
261		    	var parent = jQuery(element).closest('.liqsec-param-concepto-form');
262		    	if (parent.parent().hasClass('base-detallada'))
263		    		return jQuery.validator.format(jQuery.validator.messages.base_outside,parent.data('base-inside-max'));
264		    	else
265		    		return jQuery.validator.format(jQuery.validator.messages.max,parent.data('base-inside-max'));
266		    }
267		);
268	
269	jQuery.validator.addMethod(
270		    "validarNif",
271		    function(value, element) {
272		    	console.log('validando el nif');
273				//Si cambia el NIF volvemos a mostrar el botón para validar de nuevo
274				//quitamos los mensajes de OK o KO y los cuadros de nombre y apellido o cif
275				jQuery("#botonValidarBox").removeAttr('hidden');
276				jQuery('.iziModal #repre-plataforma-validate-response-ko').removeClass('visible').addClass('oculto');
277				jQuery('.iziModal #repre-plataforma-validate-response-ok').removeClass('visible').addClass('oculto');
278				jQuery('.iziModal #repre-plataforma-persona-fisica').removeClass('visible').addClass('oculto');
279				jQuery('.iziModal #repre-plataforma-persona-juridica').removeClass('visible').addClass('oculto');
280				
281		    	return window._NIFValidator.checkAll(value);
282		    },
283		    "El NIF/DNI/NIE indroducido no es válido."		   
284		);
285		
286	jQuery.validator.addMethod(
287		    "validarDNI",
288		    function(value, element) {
289		    	console.log('validando el DNI');
290		    	return window._NIFValidator.checkDNI(value);
291		    },
292		    "El DNI indroducido no es válido."		   
293		);
294	
295	jQuery.validator.addMethod(
296		    "validarNIE",
297		    function(value, element) {
298		    	console.log('validando el NIE');
299		    	return window._NIFValidator.checkTR(value);
300		    },
301		    "El NIE o tarjeta de residencia introducida no es válida."		   
302		);
303	
304	jQuery.validator.addMethod(
305		    "base_over",
306		    function(value, element) {
307		    	return jQuery(element).closest('.liqsec-param-concepto-form').data('base-over') != 'out';
308		    },
309		    "El valor introducido hace exceder el importe máximo por concepto: 9999999.99 €"
310		);
311	
312	jQuery.validator.addMethod(
313		    "baseParametrica",
314		    function(value, element) {
315			    
316			    var globalizedValue = value.replaceAll(".","").replace(",", ".");
317			    return this.optional(element) || (globalizedValue <= 9999999.9999 && /^\s*-?((\d{1,3}(\.(\d){3})*)|\d*)(,\d{1,4})?\s*$/.test(value)); 
318		    },
319		    "El número introducido no puede superar 9999999.9999 y sólo se admiten hasta 4 decimales"		   
320		);
321			
322	// CODIGO PARA LA VALIDACIÓN DE LA REFERENCIA CATASTRAL PASADO DESDE MADRID
323	jQuery.validator.addMethod(
324		"validarReferenciaCatastral",
325		function (refCat) 
326		{
327			if (!refCat || refCat.length !== 20) 
328			{
329		    	return false;
330		    }
331	
332		  	refCat = refCat.toUpperCase();
333		  	const dcEsperado = refCat.substring(18, 20);
334		  	const subcadena1 = refCat.substring(0, 7) + refCat.substring(14, 18);
335		  	const subcadena2 = refCat.substring(7, 14) + refCat.substring(14, 18);
336		
337		  	const dc1 = window.calcularDigitoControlReferenciaCatastral(subcadena1);
338		  	const dc2 = window.calcularDigitoControlReferenciaCatastral(subcadena2);
339		
340		  	return dcEsperado === (dc1 + dc2);
341		},
342		"La referencia catastral introducida no es válida."
343	);	
344	// FIN CODIGO DE REFERENCIA CATASTRAL
345	
346	// Validar que se ha validado la representación del NIF
347	jQuery.validator.addMethod(
348		    "nif-repre-validated",
349		    function(value, element) {
350		    	console.log('validación: validando la validación del NIF');
351		    	return sta.representacionValidada == true;
352		    }
353		);	
354	
355}
356	
357/* FUNCIONES CUSTOMIZADAS
358 * -------------------------------------------------------------------
359 */
360
361// Función que coloca el error. Solo se ejecuta la primera vez que se detecta el error:
362sta.customValidation.customErrorPlacement = function(error, element)
363{
364	var ele = jQuery(element);
365	if (error.text()=='') return;
366	//console.log('JQUERY_VALIDATION: ErrorPlacement:' + error + '. Element: ' + ele.prop('id'));
367	
368	// Se indica por accesibilidad que etiqueta indica el error del campo 
369	ele.attr('aria-errormessage',error.prop('id'));
370	error.attr('role','status');
371	
372	
373//	var direccion = ele.closest('.address-control');
374//	if (direccion.length)
375//	{
376//		var contenedorErrores = direccion.find('.wrap-error-address'); 
377//		contenedorErrores.append(error);
378//		contenedorErrores.show();
379//	}
380//	else
381	{
382		var conceptoPadre = ele.closest('html:not(.responsive) .liqsec-param-concepto-edit');
383		if (conceptoPadre.length)
384		{	
385			var contenedorErrores = jQuery('#'+ conceptoPadre.attr('id').replace('liqConceptEdit', 'liqConceptErrors')); 
386			contenedorErrores.append(error);
387		}
388		else 
389		{
390			var inlineAction = ele.closest('.inline-input-action');
391			if (inlineAction.length)
392			{
393				inlineAction.append(error);		
394			}
395			else
396			{
397				var composed = ele.closest('.field-body.composed');
398				if (composed.length)
399				{
400					if (composed.find('.composed-info').children().length == 0)
401						composed.find('.composed-info').append(error);		
402				}
403				else
404				{
405					var wrapctrl = ele.closest('.ui-in');
406					if (wrapctrl.length)
407					{
408						wrapctrl.parent().append(error);		
409					}
410					else
411					{
412						var upload = ele.closest('.widget-upload-files');
413						if (upload.length)
414						{	
415							var contenedorErrores = upload.find('.wrap-error-file'); 
416							contenedorErrores.append(error);
417							contenedorErrores.show();
418						}
419						else
420						{
421							var padre = ele.parent();
422							if (padre.hasClass('error-horizontal'))
423							{
424								padre.parent().parent().append(jQuery('<tr/>').append(jQuery('<td colspan="100"/>').append(error)));
425							}
426							else
427							{
428								padre.append(error);
429							}
430						}
431					}
432				}
433			}
434		}
435	}
436};
437
438// Función que se lanza en cada validación. Sirve para tratar de forma agrupada los mensajes de error,
439// Se lanza tanto si hay errores como si no los hay
440// Si se usa esta función no se llama al hightlight, que es para el trato indiviudal de ca
440da control.
441// Nosotros la usamos para las 2 cosas: 1. trato individual recorriendo la lista de elementos (asi no hay que sobreescribir el hightlight) 
442//								        2. buscando si hay un wrapper para incorporar ahí los errores.
443
444sta.customValidation.customErrorShow = function (e, el) {
445	console.log('JQUERY_VALIDATION: customErrorShow: errores: ' + el.length + ' , element: ' + jQuery(el).prop('id'));
446	
447	// trata por defecto:
448	this.defaultShowErrors();	
449	
450	// se tratan todos los elementos afectados individualmente:
451	jQuery(el).each(function(){
452		var field = jQuery(this.element).closest('.field');
453		if (field.length)
454		{
455			jQuery(el).attr('aria-invalid','true');		
456			field.addClass('invalid');
457			// Si es de un grupo, se marca como erroneo
458			if (field.hasClass('liqsec-param-concepto-form-box'))
459				field.closest('.liqsec-param-concepto-edit').addClass('invalidEdit');
460		}
461	});
462	
463	// Si exsite un wrapper para los errores se muestra un alert con enlace a los errores 
464	if (jQuery('.wrapErrors').length > 0 && el.length)
465	{
466		if (jQuery('*:visible > .wrapErrors .warning.informativo-inline').length == 0 )
467		{	//'<svg class="icon ' + ops.status + '"><use xlink:href="#icon-' + ops.status + '"></use></svg>'	
468			
469			
470			var elerror = jQuery('<a class="Icon warning informativo-inline" role="alert" href="javascript:;"/>').append(
471					(sta.responsive?'<svg class="icon icon-warning"><use xlink:href="#icon-warning"></use></svg>':'') 		
472			).append(sta.literales.form_error);
473			elerror.on('click',function(){
474				cleanFormErrors();      
475				window._FormValidator.form();
476			});
477			jQuery('.wrapErrors').append(elerror);			
478		}
479	}
480
481}
482//sta.customValidation.customUnhighlight = function (element, errorClass, validClass)
483//{
484//	if ( element.type === "radio" ) {
485//		this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
486//	} else {
487//		jQuery( element ).removeClass( errorClass ).addClass( validClass );
488//	}
489//}
490
491// Función que se executa cada vez que se resuelve un error en un elemento:
492// Lo usamos para el tratado extra de clases y para limpiar las 'marcas' de errores del formulario con el cleanFormErrors.
493sta.customValidation.customErrorSuccess = function (label,elemento)
494{
495	console.log('JQUERY_VALIDATION: customErrorSuccess: ' + jQuery(elemento).prop('id') + ', label: ' + label);
496	if (label.text()=='') label.remove();
497	
498	var field = jQuery(elemento).closest('.field');
499	if (field.length)
500		field.removeClass('invalid');	
501	
502	jQuery(elemento).removeClass('invalidMessage');
503	jQuery(elemento).attr('aria-invalid',null);		
504
505
506	cleanFormErrors();      
507}	
508
509// Función que se usa cuando se intenta hacer submit sobre un formulario con error/es
510sta.customValidation.customInvalidHandler = 	function(form, validator) {
511	//console.log('JQUERY_VALIDATION: InvalidHandler');
512	irAlError();
513
514}
515
516//Función para controlar cuando se trata un elemento y cuando no en el FOCUSOUT
517sta.customValidation.customOnfocusout = function (element,event){
518    if (!jQuery(element).hasClass('autocompletar') && !jQuery(element).hasClass('no-autoval') &&
519    	!this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) )
520    {
521        this.element( element );
522    }
523}
524
525// Función para controlar cuando se trata un elemento y cuando no en el KEYUP
526sta.customValidation.customOnkeyup = function (element,event){
527    if (!jQuery(element).hasClass('autocompletar') && !jQuery(element).hasClass('no-autoval') && !jQuery(element).hasClass('not-on-type') &&
528    	!this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) 
529    {
530        this.element( element );
531    }
532	
533}
534
535// Función pra limpiar los errores si ya se han resuelto:
536var cleanFormErrors = function()
537{
538	console.log('cleanFormErrors -> invalids: ' + jQuery('input.invalidMessage:visible').length);	
539	if (jQuery('input.invalidMessage:visible').length == 0)
540	{
541		if (jQuery('*:visible > .wrapErrors a').length > 0)
542		{
543			//jQuery('.wrapErrors').empty();
544			jQuery('.wrapErrors a').remove();
545			console.log('clean form -> removing');	
546		}
547	} 	
548}
549
550// Función para ir al error:
551var irAlError = function()
552{
553	var origen;
554	if (jQuery('.wrapErrors .alert').length > 0)
555			origen = jQuery(jQuery('.wrapErrors .alert')[0]);
556		else	
557			origen = jQuery(document.activeElement);
558	
559	var validator = window._FormValidator;
560	//validator.form();
561	
562	if (!validator.numberOfInvalids())
563        return;
564    var element = jQuery(validator.errorList[0].element);
565    if (element.hasClass('upload-input'))
566    	element = element.closest('.head');
567    else if (element.hasClass('required_hidden'))
568    {
569    	var next = element.next('.ui-selectmenu-button');
570    	if (next.length > 0)
571    		element = element.next();
572    }	
573    if(element.position())
574    {
575        if(element.offset().top -20 < jQuery(window).scrollTop())
576        {
577            //scroll up
578            jQuery('html,body').animate({scrollTop:element.offset().top - 20}, 800,function(){});
579            origen.effect('transfer',{ to: element, className: 'transfer-error' }, 750, function(){element.focus()});
580        }
581        else
582        {
583        	origen.effect('transfer',{ to: element, className: 'transfer-error' }, 750, function(){element.focus()});
584        }   	
585    }
586}
587	
588function destroyValidation(validator) {
589	validator.resetForm();
590
591	jQuery( validator.currentForm )
592		.off( ".validate" )
593		.removeData( "validator" )
594		.find( ".validate-equalTo-blur" )
595			.off( ".validate-equalTo" )
596			.removeClass( "validate-equalTo-blur" )
597		.find( ".validate-lessThan-blur" )
598			.off( ".validate-lessThan" )
599			.removeClass( "validate-lessThan-blur" )
600		.find( ".validate-lessThanEqual-blur" )
601			.off( ".validate-lessThanEqual" )
602			.removeClass( "validate-lessThanEqual-blur" )
603		.find( ".validate-greaterThanEqual-blur" )
604			.off( ".validate-greaterThanEqual" )
605			.removeClass( "validate-greaterThanEqual-blur" )
606		.find( ".validate-greaterThan-blur" )
607			.off( ".validate-greaterThan" )
608			.removeClass( "validate-greaterThan-blur" );
609};
610
611function buildValidations()
612{
613	configureValidations();
614	var form = jQuery(document.forms["webAppPageForm"]);
615
616	// Se destruye el anterior para asegurar que se crea el nuestro customizado:
617	//var validator = jQuery.data( form[0], "validator" );
618	//destroyValidation(validator); 
619	
620	window._FormValidator = form.validate(
621	{
622		ignore: ":hidden:not(.required_hidden), .ocultar input, .ocultar select, input[readonly],.address-control:not(:visible) *",
623		focusInvalid: false,
624		errorClass: "invalidMessage",
625		errorElement: "label",
626		errorPlacement: sta.customValidation.customErrorPlacement,
627		showErrors: sta.customValidation.customErrorShow,
628		//unhighlight: sta.customValidation.customUnhighlight,
629		success: sta.customValidation.customErrorSuccess,	
630		invalidHandler: sta.customValidation.customInvalidHandler,
631		onfocusout: sta.customValidation.customOnfocusout,
632		onkeyup: sta.customValidation.customOnkeyup
633	});
634	console.log('Applaying rules');
635	applyRules();	
636	
637	window._NIFValidator = new NIF_CIFValidator();
638	
639	//Add the new function to reset 1 field:
640	window._FormValidator['cleanElement'] = function (param_element_name) {
641	    var element_name = "";
642	    if (param_element_name.substring(0, 1) == "#") {
643	        element_name = param_element_name.substring(1);
644	    } else {
645	        element_name = param_element_name;
646	    }
647	    // Se elimina la etiqueta de error
648	    jQuery('label.invalidMessage[for=' + element_name + ']').remove();
649	    
650	    // se eliminan los estilos
651	    jQuery('#' + element_name).removeClass(this.settings.errorClass).removeClass(this.settings.validClass);
652	};	
653}
654
655function validateForm(sourceElement) {
656	
657	// si estamos dentro de un formulario modal, se lanza la prevalidación	 
658	if (jQuery(sourceElement).closest('form.iziModal').length > 0)
659	{
660		if (window._FormValidator2 != undefined)	
661			return window._FormValidator2.form();
662	}
663	else
664	{
665		if (window._FormValidator.prevalidate != undefined)
666			window._FormValidator.prevalidate();
667		return window._FormValidator.form();
668	}
669	return true
670}
671
672
673function validateFomAddCallback(funcion,append) {
674
675	console.log('añadir Pre validate callback');	
676	if (append && window._FormValidator.prevalidate != undefined)
677	{
678		prefunc = window._FormValidator.prevalidate;
679		window._FormValidator.prevalidate = function(){
680			funcion();
681			prefunc();
682		};
683	}
684	else
685		window._FormValidator.prevalidate = funcion;		 	
686}
687
688var preSetRules = new Array();
689
690var applyRules = function()
691{
692	jQuery.map(preSetRules,function(optionObject,index){
693			
694		//obj.datepicker("option", optionObject['opcion'], optionObject['valor']);
695		var fecha = jQuery("#" + optionObject['id']);
696		if (fecha.length > 0)
697		{
698			fecha.rules("add", optionObject['rule']);
699		}			
700	});
701}
702
703var addRule = function(id,valor)
704{
705	console.log('Adding rule to: '+ id);
706	var jObj = jQuery("#" + id);
707	var optionObject = { id:id,rule: valor};	
708	preSetRules.push(optionObject);
709}
710
711
712/*
713Validador de NIF, CIF, y Tarjeta de residencia por javascript.
714Sin licencia.
715Distribuido en: http://www.microteching.com/
716Autor: ticnology coop.v. (http://www.ticnology.es/)
717*/
718function NIF_CIFValidator() {
719
720this.isJuridica = function(id){
721	// Si no empieza por alguna de las letras de personas juridicas es fisica:
722	return (/^[ABCDEFGHJNPRQSUVW]/.test(id));	
723}
724	
725this.NIF_Letters = "TRWAGMYFPDXBNJZSQVHLCKET";
726this.NIF_regExp = "^\\d{8}[a-zA-Z]{1}$";
727this.CIF_regExp = "^[a-zA-Z]{1}\\d{7}[a-jA-J0-9]{1}$";
728
729this.checkAll = function (value) {
730	if (this.checkNIF(value)) { // Comprueba el CIF
731		return true;
732	} else if (this.checkESPECIALES(value)) { // Comprueba casos especiales KLM
733		return true;
734	} else if (this.checkTR(value)) { // Comprueba tarjeta de residencia
735		return true;
736	} else if (this.checkDNI(value)) { // Comprueba el NIF
737		return true;
738	} else { // Si no pasa por ninguno es false.
739		return false;
740	}
741}
742
743// VALIDA EL DNI
744this.checkDNI = function (nif) {
745	// Comprueba la longitud. Los DNI antiguos tienen 7 digitos.
746	if ((nif.length != 8) && (nif.length != 9)) return false;
747	if (nif.length == 8) nif = '0' + nif; // Ponemos un 0 a la izquierda y solucionado
748
749	// Comprueba el formato
750	var regExp = new RegExp(this.NIF_regExp);
751	if (!nif.match(regExp)) return false;
752
753	var
754	let = nif.charAt(nif.length - 1);
755	var dni = nif.substring(0, nif.length - 1)
756	var letra = this.NIF_Letters.charAt(dni % 23);
757	return (letra ==
758		let.toUpperCase());
759}
760
761//VALIDA TARJETA DE RESIDENCIA
762this.checkESPECIALES = function (tr) {
763	if (tr.length != 9) return false;
764	if ((tr.charAt(0).toUpperCase() != "K") && (tr.charAt(0).toUpperCase() != "L") && (tr.charAt(0).toUpperCase() != "M")) return false;
765	return this.checkDNI('0' + tr.substring(1, tr.length));
766}
767
768
769// VALIDA TARJETA DE RESIDENCIA
770this.checkTR = function (tr) {
771	if ((tr.length != 10) && (tr.length != 9)) return false;
772	if ((tr.charAt(0).toUpperCase() != "X") && 
773		(tr.charAt(0).toUpperCase() != "Y") &&
774		(tr.charAt(0).toUpperCase() != "Z")) return false;
775
776	var leftNum = '0';
777	if (tr.charAt(0).toUpperCase() == "Y")		
778		leftNum = '1';
779	if (tr.charAt(0).toUpperCase() == "Z")
780		leftNum = '2';
781	if (tr.length == 9) {
782		return this.checkDNI(leftNum + tr.substring(1, tr.length));
783	} else {
784		return this.checkDNI(tr.substring(1, tr.length));
785	}
786}
787
788// VALIDA NIF
789this.checkNIF = function(cif) {
790    // 1. Normalización y limpieza
791    var tempStr = cif.toUpperCase().trim();
792    
793    // 2. Validación de formato estricto: 
794    // Una letra inicial válida + 7 números + un carácter alfanumérico final
795    var regex = /^[ABCDEFGHJPQRSUVW][0-9]{7}[A-J0-9]$/;
796    if (!regex.test(tempStr)) return false;
797
798    var v1 = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
799    var suma = 0;
800
801    // 3. Cálculo del algoritmo
802    // Empezamos en i=1 para saltar la letra inicial y llegamos hasta el 7
803    for (var i = 1; i < 7; i += 2) {
804        // Posiciones impares (1, 3, 5, 7)
805        suma += v1[parseInt(tempStr.charAt(i))];
806        // Posiciones pares (2, 4, 6)
807        suma += parseInt(tempStr.charAt(i + 1));
808    }
809    // Sumamos la última posición impar (la séptima posición del string)
810    suma += v1[parseInt(tempStr.charAt(7))];
811
812    // 4. Obtener el dígito de control esperado
813    var unidad = suma % 10;
814    var digitoControlEsperado = (unidad === 0) ? 0 : 10 - unidad;
815    var letraControlEsperada = "JABCDEFGHI"[digitoControlEsperado];
816
817    // 5. El carácter de control real (posición 8)
818    var dc = tempStr.charAt(8);
819
820    // 6. Validación según el tipo de entidad
821    var letraInicial = tempStr.charAt(0);
822    
823    // Algunas entidades solo admiten letra como DC, otras solo número
824    // Pero la J (Sociedad Civil) y otras permiten ambos
825    return (dc == digitoControlEsperado) || (dc == letraControlEsperada);
826}
827
828//FUNCIONES AUXILIARES PARA LA VALIDACIÓN DE LA REFERENCIA CATASTRAL
829window.calcularDigitoControlReferenciaCatastral = 
830function (cadena) 
831{
832	const LETRAS_CONTROL = "MQWERTYUIOPASDFGHJKLBZX";
833	const PESOS = [13, 15, 12, 5, 4, 17, 9, 21, 3, 7, 1];
834    let suma = 0;
835
836	for (let i = 0; i < cadena.length; i++) 
837	{
838    	const c = cadena.charAt(i);
839	    let valor;
840	
841	    if (/\d/.test(c)) {
842	      valor = parseInt(c, 10);
843	    } else {
844	      valor = letraANumero(c);
845	    }		
846	    suma += valor * PESOS[i];
847	}
848
849  	const resto = suma % 23;
850  	return LETRAS_CONTROL.charAt(resto);
851}
852
853function letraANumero(letra) 
854{
855	if (letra === 'Ñ') 
856  	{
857    	return 15;
858  	}	
859  	const code = letra.charCodeAt(0);
860  	if (code >= 65 && code <= 78) 
861	{ // A - N
862    	return code - 65 + 1;
863  	} else if (code >= 79 && code <= 90) 
864	{ // O - Z
865    	return code - 79 + 16;
866  	} else 
867	{
868    	return 0; // carácter no válido
869  	}
870}
871//FIN FUNCIONES AUXILIARES PARA LA VALIDACIÓN DE LA REFERENCIA CATASTRAL
872
873}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.