Search code examples
regexvalidationsamplealphabet

Validating form field for a specific combination of numbers and alphabets


I need to validate a form field for a specific type of combination of numbers and alphabets:

  • first four digits are alphabets
  • next digit is zero
  • next 6 digits are numeric

e.g.
IBKL 0 001084


Solution

  • Assuming your validation is client-side:

    first four digits are alphabets next digit is zero and next 6 digits are numeric

    Compact test:

    /[a-zA-Z]{4}\s?0\s?[0-9]{6}\s?$/.test("IBKL 0 001084 ");
    /[a-zA-Z]{4}\s?0\s?[0-9]{6}\s?$/.test("IBKL 0 001084");
    /[a-zA-Z]{4}\s?0\s?[0-9]{6}\s?$/.test("IBKL0001084");
    

    Verbose test:

    var first_four = "[a-zA-Z]{4}",  zero = "0",  next_six = "[0-9]{6}", space_maybe = "\\s?", end = "$";
    
    RegExp(first_four + space_maybe + zero + space_maybe + next_six + space_maybe + end).test("IBKL 0 001084 ");
    
    RegExp(first_four + space_maybe + zero + space_maybe + next_six + space_maybe + end).test("IBKL 0 001084");
    
    RegExp(first_four + space_maybe + zero + space_maybe + next_six + space_maybe + end).test("IBKL0001084");