Blog article

Code snippets, plus the latest news

lbfl ConsultancyContact form 7 Javascript numbers only text field UncategorizedCF7 text field with min/max character that accept only digits – simple how to.

CF7 text field with min/max character that accept only digits – simple how to.

Contact form 7 text field that accepts number only.

Quite some time ago I stumbled upon a post about only allowing numbers in a text field of Contact Form 7. The post is here:

Obviously a number of readers spotted the code, implemeted the same and then asked about applying the solution to more than one form field in the same way. The solutions  is really simple and I’ve built this on the code supplied by Yordan Soares. There are other methods of acheiving the same result, but as the thread was closed some time ago I thought that I’d supply a solution.

The Javascript.

Place this in your themes functions.php , preferably use a child theme.

add_action( 'wp_footer', 'wpcf7_input_numbers_only');
function wpcf7_input_numbers_only() {
  echo '
  onload =function (){ 
    var ele = document.querySelectorAll(\'.wpcf7-numbers-only\')[0]; //first form field class
    var sort = document.querySelectorAll(\'.wpcf7-sort-only\')[0]; //second form field class
    ele.onkeypress = function(e) {
      return false;
    ele.onpaste = function(e){
    sort.onkeypress = function(e) {
      return false;
    sort.onpaste = function(e){

Contact form 7 code.

An extract from a contact form 7 is shown below and the fields are shown to the right. It’s that simple.

CF7 text field accepting only numbers
<div class="row">
   <div class="col">
        <p>Bank/Building society Account Number <span style="color:#f00;font-weight:bold;">*</span></p>
            [text* Account_no class:wpcf7-numbers-only minlength:8 maxlength:8  placeholder "Account number"]
        <p>Branch Sort Code <span style="color:#f00;font-weight:bold;">*</span></p>
            [text* Sort_code class:wpcf7-sort-only minlength:6 maxlength:6 placeholder "Sort Code"]