Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Prevent user inputting characters not in regex

I have an input field called exampleInput. I want the user only can write these two:

var pattern = /[A-Za-z][0-9]{7}[A-Za-z0-9]/;
var pattern2 = /^[XYZ][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/i;

If they try to write a number or a string which does not match the patterns, stop the character from being shown. How can Ido that?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to break it down into multiple patterns and check all possible states. Your first pattern has no start or end, not sure if that's what you want? In my example I'll go with pattern = /^[A-Za-z][0-9]{7}[A-Za-z0-9]$/ We can check for first letter and numbers in p0 = /^[A-Za-z][0-9]{0,7}$/ And then we have it all set, if value does not follow p0 nor pattern, block it. You can surely do more advanced regex but readability drops fast.

    document.getElementById('exampleInput').addEventListener('keydown', (e) => {
        if (["Backspace","Delete","Enter","ArrowLeft","ArrowRight"].indexOf(e.key) >= 0) { return; }
        var value = e.target.value.substring(0, e.target.selectionStart) + e.key + e.target.value.substring(e.target.selectionEnd);
        var pattern = /^[A-Za-z][0-9]{7}[A-Za-z0-9]$/;
        var p0 = /^[A-Za-z][0-9]{0,7}$/
        if (!p0.test(value) && !pattern.test(value)) {
            e.preventDefault();
        }
    })
<input id="exampleInput">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!