Home / Admin / Real-time validation for restricting numbers from Single Line Text field
Duplicate Snippet

Embed Snippet on Your Site

Real-time validation for restricting numbers from Single Line Text field

<10
Code Preview
js
/**
 * Dynamically prevent numbers from being entered on single line text fields
 *
 * @link https://wpforms.com/developers/how-to-restrict-numbers-in-a-single-line-text-form-field/
 */
 
function wpf_dev_restrict_numbers( ) {
?>
  <script type="text/javascript">
    (function($) {
      var No_Numbers_Custom_Validation = {
        init: function() {
          $(document).on( 'wpformsReady', No_Numbers_Custom_Validation.customRules);
        },
        customRules: function() {
          if (typeof $.fn.validate !== 'undefined') { 
            $.validator.addMethod( "check_for_number", function(value, element, param) {
              var $ele = $(element);
              return this.optional(element) || ! /\d/.test(value);
            }, $.validator.format( "This field cannot accept numbers." ));
          }
          if ( $( '.no-numbers input' ).length ) {
            $( '.no-numbers input' ).rules( 'add', {
              check_for_number: true
            });             
          }
        },
      }
      No_Numbers_Custom_Validation.init();
    })(jQuery);
  </script>
<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_restrict_numbers', 30 );

Comments

Add a Comment