How to Create an Input Widget that Enforce Six Digit Input in Forms

Overview

This article explains how to build an input widget that helps to enter a six-digit code for a custom implementation.

Requirements:

  1. The digit length should be 6
  2. All entries should be numbers between 0 to 9

Applies To

  • Forms

Solution

A custom field component can help to implement this requirement as it allows customization with Code.

Here is a sample code that would satisfy the requirements.

function customTextInput() {
  const input = document.createElement('input');
  input.type = 'string';

  return {
    init() {
      return input;
    },

    getValue() {
      if (parseInt(input.value) != input.value) {
        throw new Error('The input must only contain numbers')
      }
      if (input.value.length != 6) {
        throw new Error('The length must be 6 digit')
      }
      return input.value;
    }
  };
}