Plugin Directory

Changeset 2577010


Ignore:
Timestamp:
08/03/2021 09:42:31 AM (5 years ago)
Author:
davidsancho4
Message:

Nuevo Añadida una etiqueta identidad

Location:
validar-identidad-cf7/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • validar-identidad-cf7/trunk/readme.txt

    r2574813 r2577010  
    44Requires at least: 5.8
    55Tested up to: 5.8
    6 Stable tag: 1.0
     6Stable tag: 1.1
    77License: GPLv2 or later
    88License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    4949Para poder introducir en Contact Form 7 un campo para validar un DNI, NIF, NIE o CIF, es necesario utilizar una de las siguientes etiquetas:
    5050
    51 - Si quiere que el campo sea obligatorio: [text* identidad-nombre]
    52 
    53 - Si no quiere que el campo sea obligatorio: [text identidad-nombre]
     51Se ha añadido una nueva etiqueta llamada identidad
    5452
    5553<strong>¿Funciona con documentos de identidad de otros países?</strong>
     
    6058
    6159Sin guiones ni espacios. Da igual si la letra o letras están en mayúsculas o minúsculas.
     60
     61<strong>¿Se puede personalizar el mensaje de error?</strong>
     62Si, dentro de Mensajes encontraras 'Validación DNI, NIF, NIE o CIF'. Allí podrás escribir un mensaje personalizado, utilizando {{identificador}} utilizarás el tipo de identidad automáticamente.
  • validar-identidad-cf7/trunk/validar-identidad-cf7.php

    r2574813 r2577010  
    11<?php
    2   /*
    3     Plugin Name: Validar identidad CF7
    4     Plugin URI: https://www.david-sancho.com
    5     Description: Poder validar los campos del DNI, NIF, NIE y CIF con el plugin Contact Form 7
    6     Version: 1.0
    7     Author: David Sancho
    8     Author URI: https://www.david-sancho.com   
    9     License: GPLv2 or later
    10     Text Domain: videntidad
    11    
    12     # LICENSE   
    13     This program is free software; you can redistribute it and/or modify
    14     it under the terms of the GNU General Public License, version 2, as
    15     published by the Free Software Foundation.
    16    
    17     This program is distributed in the hope that it will be useful,
    18     but WITHOUT ANY WARRANTY; without even the implied warranty of
    19     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    20     GNU General Public License for more details.
    21    
    22     You should have received a copy of the GNU General Public License
    23     along with this program; if not, write to the Free Software
    24     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    25    
    26   */
    27   include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
    28  
    29   add_action('admin_notices', 'cf7_requerido_action');
    30  
    31   if(!function_exists('cf7_requerido_action'))
    32   {
    33     function cf7_requerido_action()
    34     {
    35       $cf7_validar_messages = "";
    36      
    37       if ( file_exists( WP_PLUGIN_DIR . '/contact-form-7/wp-contact-form-7.php' ) ){
    38         if(!is_plugin_active( 'contact-form-7/wp-contact-form-7.php' ))
    39         {
    40           $cf7_validar_messages = 'El plugin validación DNI-NIF-NIE-CIF requiere que el plugin Contact Form 7 esté activado';
    41         }
    42         }else{
    43        
    44         $cf7_validar_messages = 'El plugin validación DNI-NIF-NIE-CIF requiere el plugin Contact Form 7, <a href="https://wordpress.org/plugins/contact-form-7/">descargalo aquí</a>.';
    45       }
    46      
    47       if(!empty($cf7_validar_messages))
    48       {
    49         echo '<div id="message" class="error cf7_validar_messages">';     
    50        
    51         echo '<p class="cf7_validar_messages"><b>'. esc_html_e($cf7_validar_messages, 'videntidad').'</b></p>';     
    52        
    53         echo '</div>';
    54       }
    55     }
    56   }
    57  
    58   if ( file_exists( WP_PLUGIN_DIR . '/contact-form-7/wp-contact-form-7.php' ) )
    59   {
    60     if(is_plugin_active( 'contact-form-7/wp-contact-form-7.php' ))
    61     {     
    62       if(!function_exists('cf7_validation_callback_action'))
    63       {
    64         // validation_callback_action
    65         function cf7_validation_callback_action($identidad) {
    66          
    67           $identidad = strtoupper($identidad);
    68           for ($i = 0; $i < 9; $i ++)
    69           {
    70             $num_array[$i] = substr($identidad, $i, 1);
    71           }
    72          
    73           if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $identidad))
    74           {
    75             return 0;
    76           }
    77          
    78           if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $identidad))
    79           {
    80             if ($num_array[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($identidad, 0, 8) % 23, 1))
    81             {
    82               return 1;
     2
     3/**
     4 * Plugin Name: Validar identidad CF7
     5 * Plugin URI: https://davidsancho4.wordpress.com/
     6 * Description: Poder validar los campos del DNI, NIF, NIE y CIF con el plugin Contact Form 7
     7 * Version: 1.1
     8 * Author: David Sancho
     9 * Author URI: https://davidsancho4.wordpress.com/
     10 * License: GPLv2 or later
     11 * Text Domain: videntidad
     12 *
     13 * # LICENSE
     14 * This program is free software; you can redistribute it and/or modify
     15 * it under the terms of the GNU General Public License, version 2, as
     16 * published by the Free Software Foundation.
     17 *
     18 * This program is distributed in the hope that it will be useful,
     19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
     20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     21 * GNU General Public License for more details.
     22 *
     23 * You should have received a copy of the GNU General Public License
     24 * along with this program; if not, write to the Free Software
     25 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     26 */
     27
     28include_once(ABSPATH . 'wp-admin/includes/plugin.php');
     29
     30add_action('admin_notices', 'cf7_requerido_action');
     31
     32if (!function_exists('cf7_requerido_action')) {
     33    function cf7_requerido_action() {
     34        $cf7_validar_messages = "";
     35
     36        if (file_exists(WP_PLUGIN_DIR . '/contact-form-7/wp-contact-form-7.php')) {
     37            if (!is_plugin_active('contact-form-7/wp-contact-form-7.php')) {
     38                $cf7_validar_messages = 'El plugin validación DNI-NIF-NIE-CIF requiere que el plugin Contact Form 7 esté activado';
    8339            }
    84             else
    85             {
    86               return -1;
     40        } else {
     41            $cf7_validar_messages = 'El plugin validación DNI-NIF-NIE-CIF requiere el plugin Contact Form 7, <a href="https://wordpress.org/plugins/contact-form-7/">descargalo aquí</a>.';
     42        }
     43
     44        if (!empty($cf7_validar_messages)) {
     45            echo '<div id="message" class="error cf7_validar_messages">';
     46            echo '<p class="cf7_validar_messages"><b>'. esc_html_e($cf7_validar_messages, 'videntidad').'</b></p>';
     47            echo '</div>';
     48        }
     49    }
     50}
     51
     52if (file_exists(WP_PLUGIN_DIR . '/contact-form-7/wp-contact-form-7.php')) {
     53    if (is_plugin_active('contact-form-7/wp-contact-form-7.php')) {
     54        if (!function_exists('cf7_validation_callback_action')) {
     55            // validation_callback_action
     56            function cf7_validation_callback_action($identidad) {
     57                $identidad = strtoupper($identidad);
     58
     59                for ($i = 0; $i < 9; $i ++) {
     60                    $num_array[$i] = substr($identidad, $i, 1);
     61                }
     62
     63                if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $identidad)) {
     64                    return 0;
     65                }
     66
     67                if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $identidad)) {
     68                    if ($num_array[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($identidad, 0, 8) % 23, 1)) {
     69                        return 'cf-validate-dni';
     70                    } else {
     71                        return -1;
     72                    }
     73                }
     74
     75                $sum_pattern = $num_array[2] + $num_array[4] + $num_array[6];
     76
     77                for ($i = 1; $i < 8; $i += 2) {
     78                    $sum_pattern += substr((2 * $num_array[$i]), 0, 1) + substr((2 * $num_array[$i]), 1, 1);
     79                }
     80
     81                $n = 10 - substr($sum_pattern, strlen($sum_pattern) - 1, 1);
     82
     83                if (preg_match('/^[KLM]{1}/', $identidad)) {
     84                    if ($num_array[8] == chr(64 + $n) || $num_array[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($identidad, 1, 8) % 23, 1)) {
     85                        return 'cf-validate-nif';
     86                    } else {
     87                        return -1;
     88                    }
     89                }
     90
     91                if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $identidad)) {
     92                    if ($num_array[8] == chr(64 + $n) || $num_array[8] == substr($n, strlen($n) - 1, 1)) {
     93                        return 'cf-validate-cif';
     94                    } else {
     95                        return -2;
     96                    }
     97                }
     98
     99                if (preg_match('/^[XYZ]{1}/', $identidad)) {
     100                    if ($num_array[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $identidad), 0, 8) % 23, 1)) {
     101                        return 'cf-validate-nie';
     102                    } else {
     103                        return -3;
     104                    }
     105                }
     106
     107                return 0;
    87108            }
    88           }
    89          
    90           $sum_pattern = $num_array[2] + $num_array[4] + $num_array[6];
    91           for ($i = 1; $i < 8; $i += 2)
    92           {
    93             $sum_pattern += substr((2 * $num_array[$i]),0,1) + substr((2 * $num_array[$i]), 1, 1);
    94           }
    95           $n = 10 - substr($sum_pattern, strlen($sum_pattern) - 1, 1);
    96          
    97           if (preg_match('/^[KLM]{1}/', $identidad))
    98           {
    99             if ($num_array[8] == chr(64 + $n) || $num_array[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($identidad, 1, 8)
    100             % 23, 1))
    101             {
    102               return 1;
     109        }
     110
     111        if (!function_exists('cf7_validacion_nif_cif_nie')) {
     112            function cf7_validacion_nif_cif_nie($results, $tag) {
     113                $result_actual = $results['valid'];
     114                $field_data = sanitize_text_field($_POST[$name]);
     115                $type = $tag['basetype'];
     116                $name = $tag['name'];
     117
     118                if ($type == 'identidad*') {
     119                    $results->invalidate($tag, wpcf7_get_message('invalid_identidad'));
     120                }
     121
     122                $identidad = sanitize_text_field($_POST[$name]);
     123
     124                if ($identidad != '') {
     125                    $validated_identidad = cf7_validation_callback_action($identidad);
     126                    $allowed_types = explode(',', $_POST['__identificacion']);
     127
     128                    if (!in_array($validated_identidad, $allowed_types, true)) {
     129                        $message = wpcf7_get_message('invalid_identidad');
     130
     131                        if (!empty($allowed_types)) {
     132                            $str = ''; $result = [];
     133
     134                            foreach ($allowed_types as $type) {
     135                                $result[] = strtoupper(substr($type, strlen('cf-validate-')));
     136                            }
     137
     138                            $str .= implode(', ', $result);
     139
     140                            $message = str_replace("{{identificador}}", $str, $message);
     141                        }
     142
     143                        $results->invalidate($tag, $message);
     144                    } else {
     145                        if ($result_actual == false) {
     146                            $results['valid'] = false;
     147                        } else {
     148                            $results['valid'] = true;
     149                        }
     150                    }
     151                }
     152                //output
     153                return $results;
    103154            }
    104             else
    105             {
    106               return -1;
     155        }
     156        //Add Filter Validación HOOK
     157        add_filter('wpcf7_validate_identidad', 'cf7_validacion_nif_cif_nie', 10, 2);
     158        add_filter('wpcf7_validate_identidad*', 'cf7_validacion_nif_cif_nie', 10, 2);
     159    }
     160
     161    if (!function_exists('cf7_nif_cif_nie_validacion_message')) {
     162        function cf7_nif_cif_nie_validacion_message($messages) {
     163            return array_merge(
     164                $messages,
     165                array(
     166                    'invalid_identidad' => array(
     167                    'description' => __("Validacion DNI, NIF, NIE o CIF", 'contact-form-7'),
     168                    'default' => __("Escribe un DNI, NIF, NIE o CIF válido", 'contact-form-7'),
     169                ),
     170            )
     171            );
     172        }
     173    }
     174    /* wpcf7_messages HOOK*/
     175    add_filter('wpcf7_messages', 'cf7_nif_cif_nie_validacion_message', 10, 1);
     176
     177    add_action('wpcf7_init', 'custom_add_form_tag_identidad');
     178
     179    function custom_add_form_tag_identidad() {
     180        wpcf7_add_form_tag(
     181            array('identidad', 'identidad*'),
     182            'custom_identidad_form_tag_handler',
     183            array(
     184                'name-attr' => true,
     185                'selectable-values' => true,
     186                'multiple-controls-container' => true,
     187            )
     188        );
     189    }
     190
     191    function custom_identidad_form_tag_handler($tag) {
     192        $tag = new WPCF7_FormTag($tag);
     193        $defined_types = ['cf-validate-dni', 'cf-validate-cif', 'cf-validate-nie', 'cf-validate-nif'];
     194
     195        if (empty($tag->name)) {
     196            return '';
     197        }
     198
     199        $validation_error = wpcf7_get_validation_error($tag->name);
     200
     201        $atts = array();
     202
     203        $class = wpcf7_form_controls_class($tag->type);
     204        $atts['class'] = $tag->get_class_option($class);
     205
     206        if ($validation_error) {
     207            $class .= ' wpcf7-not-valid';
     208        }
     209
     210        $atts['id'] = $tag->get_id_option();
     211        $allowed_types = array();
     212
     213        //push all of custom selected types
     214        foreach ($tag->values as $key => $value) {
     215            if (!in_array($value, $defined_types) && $key === 0)
     216                continue;
     217           
     218            array_push($allowed_types, $value);
     219        }
     220
     221        $value = (string) reset($tag->values);
     222
     223        if ($tag->has_option('placeholder') or $tag->has_option('watermark')) {
     224            $atts['placeholder'] = $value;
     225            $value = '';
     226        }
     227
     228        $value = $tag->get_default_option($value);
     229
     230        $value = wpcf7_get_hangover($tag->name, $value);
     231
     232        $atts['value'] = in_array($value, $defined_types) ? '' : $value;
     233
     234        $atts['name'] = $tag->name;
     235        $atts = wpcf7_format_atts($atts);
     236
     237        $html = sprintf(
     238            '<span class="wpcf7-form-control-wrap %1$s"><input name="__identificacion" type="hidden" value="' . implode(',', $allowed_types) . '"><input type="text" %2$s />%3$s</span>',
     239            sanitize_html_class($tag->name),
     240            $atts,
     241            $validation_error
     242        );
     243        return $html;
     244    }
     245
     246    /* Tag generator */
     247    add_action('wpcf7_admin_init', 'wpcf7_add_tag_generator_identidad', 99, 0);
     248    function wpcf7_add_tag_generator_identidad() {
     249        $tag_generator = WPCF7_TagGenerator::get_instance();
     250        $tag_generator->add('identidad', __('identidad', 'contact-form-7'), 'wpcf7_tag_generator_identidad');
     251    }
     252
     253    function wpcf7_tag_generator_identidad($contact_form, $args = '') {
     254        $args = wp_parse_args($args, array());
     255        $type = 'identidad';
     256
     257        $description = __("Generate a form-tag for a identidad input field.", 'contact-form-7');
     258?>
     259        <div class="control-box">
     260            <fieldset>
     261                <legend><?php echo sprintf(esc_html($description)); ?></legend>
     262
     263                <table class="form-table">
     264                    <tbody>
     265                        <tr>
     266                            <th scope="row"><?php echo esc_html(__('Field type', 'contact-form-7')); ?></th>
     267                            <td>
     268                                <fieldset>
     269                                    <legend class="screen-reader-text"><?php echo esc_html(__('Field type', 'contact-form-7')); ?></legend>
     270                                    <label><input type="checkbox" name="required" /> <?php echo esc_html(__('Required field', 'contact-form-7')); ?></label>
     271                                </fieldset>
     272                            </td>
     273                        </tr>
     274
     275                        <tr>
     276                            <th scope="row"><label for="<?php echo esc_attr($args['content'] . '-name'); ?>"><?php echo esc_html(__('Name', 'contact-form-7')); ?></label></th>
     277                            <td><input type="text" name="name" class="tg-name oneline" id="<?php echo esc_attr($args['content'] . '-name'); ?>" /></td>
     278                        </tr>
     279
     280                        <tr>
     281                            <th scope="row"><label for="<?php echo esc_attr($args['content'] . '-values'); ?>"><?php echo esc_html(__('Default value', 'contact-form-7')); ?></label></th>
     282                            <td><input type="text" id="identidad-values" name="values" class="oneline" id="<?php echo esc_attr($args['content'] . '-values'); ?>" /><br />
     283                            <label><input type="checkbox" name="placeholder" class="option" /> <?php echo esc_html(__('Use this text as the placeholder of the field', 'contact-form-7')); ?></label></td>
     284                        </tr>
     285
     286                        <tr>
     287                            <th scope="row"><label for="<?php echo esc_attr($args['content'] . '-id'); ?>"><?php echo esc_html(__('Id attribute', 'contact-form-7')); ?></label></th>
     288                            <td><input type="text" name="id" class="idvalue oneline option" id="<?php echo esc_attr($args['content'] . '-id'); ?>" /></td>
     289                        </tr>
     290
     291                        <tr>
     292                            <th scope="row"><label for="<?php echo esc_attr($args['content'] . '-class'); ?>"><?php echo esc_html(__('Class attribute', 'contact-form-7')); ?></label></th>
     293                            <td><input type="text" name="class" class="classvalue oneline option" id="<?php echo esc_attr($args['content'] . '-class'); ?>" /></td>
     294                        </tr>
     295
     296                        <tr>
     297                            <th scope="row"><label for="<?php echo esc_attr($args['content'] . '-identificacion'); ?>"><?php echo esc_html(__('Identificacion attribute', 'contact-form-7')); ?></label></th>
     298                            <td>
     299                                <select name="identificacion_select" id="identificacion_select" class="identificacion_selectvalue oneline option" id="<?php echo esc_attr($args['content'] . '-identificacion_select'); ?>">
     300                                    <option value="-1">ALL</option>
     301                                    <option value="0">Custom</option>
     302                                </select><br><br>
     303
     304                                <div id="identificacion" style="display: none;">
     305                                    <label for="dni" style="margin-right: 10px;">
     306                                        <input checked type="checkbox" class="dnivalue identificacion" name="identificacion" id="dni" value="cf-validate-dni"> DNI
     307                                    </label>
     308                                    <label for="nif" style="margin-right: 10px;">
     309                                        <input checked type="checkbox" class="nifvalue identificacion" name="identificacion" id="nif" value="cf-validate-nif"> NIF
     310                                    </label>
     311                                    <label for="cif" style="margin-right: 10px;">
     312                                        <input checked type="checkbox" class="cifvalue identificacion" name="identificacion" id="cif" value="cf-validate-cif"> CIF
     313                                    </label>
     314                                    <label for="nie" style="margin-right: 10px;">
     315                                        <input checked type="checkbox" class="nievalue identificacion" name="identificacion" id="nie" value="cf-validate-nie"> NIE
     316                                    </label>
     317                                </div>
     318                            </td>
     319                        </tr>
     320                    </tbody>
     321                </table>
     322            </fieldset>
     323        </div>
     324
     325        <div class="insert-box">
     326            <input type="text" name="<?php echo $type; ?>" class="tag code" readonly="readonly" onfocus="this.select()" />
     327
     328            <div class="submitbox">
     329                <button id="identidad-btn" class="button button-primary insert-tag"><?php echo esc_attr(__('Insert Tag', 'contact-form-7')); ?></button>
     330                <input class="button button-primary insert-tag" name="_identidad_btn" type="button" style="display: none;">
     331            </div>
     332
     333            <br class="clear" />
     334
     335            <p class="description mail-tag"><label for="<?php echo esc_attr($args['content'] . '-mailtag'); ?>"><?php echo sprintf(esc_html(__("To use the value input through this field in a mail field, you need to insert the corresponding mail-tag (%s) into the field on the Mail tab.", 'contact-form-7')), '<strong><span class="mail-tag"></span></strong>'); ?><input type="text" class="mail-tag code hidden" readonly="readonly" id="<?php echo esc_attr($args['content'] . '-mailtag'); ?>" /></label></p>
     336        </div>
     337
     338        <script type="text/javascript">
     339            jQuery(document).ready(function() {
     340                jQuery(document).on('change', "[data-id='identidad']", function() {
     341                    updateShortcode();
     342                });
     343
     344                jQuery(document).on('change', '#identificacion_select', function() {
     345                    var $this = jQuery(this);
     346                    var $options = jQuery('#identificacion');
     347
     348                    if ($this.val() == -1) {
     349                        jQuery('.identificacion').prop('checked', true);
     350                        $options.hide();
     351                    } else {
     352                        jQuery('.identificacion').prop('checked', false);
     353                        $options.show();
     354                    }
     355                });
     356
     357                jQuery(document).on('click', '#identidad-btn', function(e) {
     358                    if (validateIdentificationForm() === true) {
     359                        jQuery('input[name="_identidad_btn"]').trigger("click");
     360                    }
     361                })
     362            });
     363
     364            function updateShortcode() {
     365                var identificacions = [];
     366                var $shortcode = jQuery(document).find("[name='identidad']");
     367
     368                jQuery('.identificacion:checked').each(function(key, item) {
     369                    var $item = jQuery(item);
     370                    identificacions.push('"' + $item.val() + '"');
     371                });
     372
     373                $shortcode.val($shortcode.val().replace(']', ' ') + identificacions.join(' ') + ']');
    107374            }
    108           }
    109          
    110           if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $identidad))
    111           {
    112             if ($num_array[8] == chr(64 + $n) || $num_array[8] == substr($n, strlen($n) - 1, 1))
    113             {
    114               return 2;
     375
     376            function validateIdentificationForm() {
     377                var $value = jQuery("#identidad-values");
     378                var types = ['cf-validate-dni', 'cf-validate-nif', 'cf-validate-cif', 'cf-validate-nie'];
     379                var $options = jQuery('.identificacion:checked');
     380               
     381                $value.closest('td').find('span').remove();
     382                jQuery('#identificacion span').remove();
     383
     384                if (types.includes($value.val().toLowerCase())) {
     385                    $value.closest('td').append('<span style="color: #ff0000; display: block;">El valor no debe ser DNI, NIF, CIF, NIE.</span>');
     386
     387                    return false;
     388                }
     389
     390                if ($options.length <= 0) {
     391                    jQuery('#identificacion').append('<span style="color: #ff0000; display: block">Se debe seleccionar al menos uno.</span>');
     392
     393                    return false;
     394                }
     395
     396                return true;
    115397            }
    116             else
    117             {
    118               return -2;
    119             }
    120           }
    121          
    122           if (preg_match('/^[XYZ]{1}/', $identidad))
    123           {
    124             if ($num_array[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'),
    125             array('0','1','2'), $identidad), 0, 8) % 23, 1))
    126             {
    127               return 3;
    128             }
    129             else{
    130               return -3;
    131             }
    132           }
    133           return 0;
    134         }
    135       }
    136      
    137       if(!function_exists('cf7_validacion_nif_cif_nie'))
    138       {
    139         function cf7_validacion_nif_cif_nie($results, $tag) {
    140           $result_actual = $results['valid'];
    141           $field_data = sanitize_text_field($_POST[$name]);
    142           $type = $tag['basetype'];
    143           $name = $tag['name'];
    144           if($type == 'text*' && $field_data == '' && stripos($name, 'identidad-') !== false){
    145             $results->invalidate( $tag, wpcf7_get_message( 'invalid_identidad' ) );
    146           }
    147          
    148           if(stripos($name, 'identidad-') !== false) {
    149             $identidad = sanitize_text_field($_POST[$name]);
    150            
    151             if($identidad != '') {
    152               if(cf7_validation_callback_action($identidad) == 0 || cf7_validation_callback_action($identidad) == -1 || cf7_validation_callback_action($identidad) == -2
    153               || cf7_validation_callback_action($identidad) == -3){
    154                 $results->invalidate( $tag, wpcf7_get_message( 'invalid_identidad' ) );                     
    155                
    156                 }else{
    157                 if($result_actual == false){
    158                   $results['valid'] = false;
    159                   }else{
    160                   $results['valid'] = true;
    161                 }
    162               }         
    163             }
    164           }
    165           //output         
    166           return $results;
    167          
    168         }
    169       } 
    170       //Add Filter Validación HOOK
    171       add_filter( 'wpcf7_validate_text', 'cf7_validacion_nif_cif_nie', 10, 2 );
    172       add_filter( 'wpcf7_validate_text*', 'cf7_validacion_nif_cif_nie', 10, 2 );
    173     }
    174    
    175     if(!function_exists('cf7_nif_cif_nie_validacion_message'))
    176     {
    177       function cf7_nif_cif_nie_validacion_message($messages)
    178       {
    179        
    180         return array_merge( $messages, array(
    181         'invalid_identidad' => array(
    182         'description' => __( "Validacion DNI, NIF, NIE o CIF", 'contact-form-7' ),
    183         'default' => __( "Escribe un DNI, NIF, NIE o CIF válido", 'contact-form-7' ),
    184         ),
    185        
    186        
    187         ) );
    188        
    189        
    190       }
    191     }
    192     /* wpcf7_messages HOOK*/   
    193     add_filter( 'wpcf7_messages', 'cf7_nif_cif_nie_validacion_message', 10, 1 );
    194   } 
     398        </script>
     399
     400<?php
     401    }
     402}
    195403?>
Note: See TracChangeset for help on using the changeset viewer.