Auto Input Validation Form Fields

You can use input masks so that when a user types input into a form field, they will have automatic input field validation. See the USWDS page for examples of valid input mask examples and best practices. This is best used for zip codes and phone numbers, but can also be used for validations ID numbers with static inputs as well.

It would also be helpful to be familiar with regex as well.

The JS

Depending on what type of input you use, you will have to validate for the many different ways a user might fill out a field.

  • Line 4-5: You want the user to allow the ability to use backspaces/delete input.

  • Line 7-10: Rejects special characters and spaces.

  • Line 13-19: Automatically adds spaces based on what position. The charAt() starts at 0.

  • Line 21: Sets the max character input. This includes spaces.

  • Line 22: Defines text inside the input but has no value. Useful for displaying a hint to user of what the input should look like.

// The example is used for the 'XXX XX XXXX' input only
$(document).on('knack-view-render.any', function (event, view, data) {
  $('input#field_XXX').keyup(function(event) { // When inputting the field
    this.value = this.value.replace(/[-]/g, ''); // replace hyphens with nothing
    if (event.key === 'Backspace') { // ignore if backspace
      return;
    } else if (event.key === ' ') { // reject " "
      this.value = this.value.replace(/[\s]/g, ''); // replace space with nothing
    } else if (isNaN(Number(event.key))) { // if not number
      this.value = this.value.replace(/[^0-9\s-]+/g, '');
    }
    
    // Auto adds spacing at 4th and 7th position.
    if (this.value.charAt(3) != " "){ // replace if no space at 4th position
      this.value = this.value.replace(/^(.{3})(.*)$/, "$1 $2"); 
    }
    if (this.value.charAt(6) != " "){ // replace if no spaces at 7th position
      this.value = this.value.replace(/^(.{6})(.*)$/, "$1 $2");
    }
  });
  $("input#field_XXX").attr('maxlength', 11); // Max input 11 characters
  $("input#field_XXX").attr('placeholder',"___ __ ____");
});

The CSS

None.

Last updated