Prevent Non-numeric Characters in Input

Experimental Snippet 🧪

Based on solution provided here: https://stackoverflow.com/a/15729184/227711

Instructions

  1. Install this snippet with our free Custom JavaScript plugin. https://gravitywiz.com/gravity-forms-code-chest/
  2. Configure snippet for your form based on inline instructions.

Code

Filename: gw-prevent-non-numeric-chars.js

/**
 * Gravity Wiz // Gravity Forms // Prevent Non-numeric Characters in Input
 * https://gravitywiz.com/
 *
 * Experimental Snippet 🧪
 *
 * Based on solution provided here: https://stackoverflow.com/a/15729184/227711
 *
 * Instructions:
 *
 * 1. Install this snippet with our free Custom JavaScript plugin.
 *    https://gravitywiz.com/gravity-forms-code-chest/
 * 2. Configure snippet for your form based on inline instructions.
 */
// Update "1" to your field ID.
document.getElementById( 'input_GFFORMID_1' ).onkeypress = function( e ) {
    e = e || window.event;
    var charCode = ( typeof e.which == 'undefined' ) ? e.keyCode : e.which;
    var charStr = String.fromCharCode( charCode );
    if ( ! /\d/.test( charStr ) ) {
        return false;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.