Search code examples
jqueryvalidationinputcharacterstring-length

Validate specific structure of input field


I really need help on this one... I have an input field that needs a very specific validation. these are the rules:

  1. it must be max 5 characters (but can have less)
  2. first 4 characters must be only numbers, the fifth character must be a letter.

So far I have manged to validate the length, and test the whole string for numbers. What I can't figure out is how to only test a part of the string for numbers (and text for the other part)

Here is the code I am using:

$(document).ready(function() {
    $('.input-text').on('change', function() { 
        if ($(this).val().length>5) {
            alert( 'Sorry... Maximum of 5 characters allowed' );
            var res = $(this).val().substring(0, 4);
            $(this).val(res);
        }

        if ( $(this).val() &&  !$(this).isNumeric ) {
            alert("Numbers Only Please");
            $(this).val('');
        }
    })
});

Thanks in advance


Solution

  • One option is to slice the 0th to 3rd, and the 4th character from the string, then check that the first matches ^\d*$ (all digits), and the last character, if it exists, matches [a-z] (alphabetical):

    $('.input-text').on('change', function() {
      const val = $(this).val();
      if (val.length > 5) {
        console.log('Sorry... Maximum of 5 characters allowed');
        $(this).val(val.slice(0, 4));
      }
      const firstFour = val.slice(0, 4);
      const fifth = val[4];
      if (!/^\d*$/.test(firstFour)) {
        console.log('First four must be numeric only');
        $(this).val('');
        return;
      }
      if (fifth && !/[a-z]/i.test(fifth)) {
        console.log('Fifth must be alphabetical');
        $(this).val(firstFour);
      }
    })
    <input class="input-text">

    Could also do it in a single regular expression, but then you can't differentiate out the different sorts of problems the input might have.

    Also, no need for jQuery for something this trivial, you could remove the dependency on it and make the syntax look a bit cleaner if you wished:

    document.querySelector('.input-text').addEventListener('change', function() {
      const val = this.value
      if (val.length > 5) {
        console.log('Sorry... Maximum of 5 characters allowed');
        this.value = val.slice(0, 4);
      }
      const firstFour = val.slice(0, 4);
      const fifth = val[4];
      if (!/^\d*$/.test(firstFour)) {
        console.log('First four must be numeric only');
        this.value = '';
        return;
      }
      if (fifth && !/[a-z]/i.test(fifth)) {
        console.log('Fifth must be alphabetical');
        this.value = firstFour;
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input class="input-text">