-1

I have an input field on a registration screen where the user has to enter his user id which is generally 6 characters long. First 2 characters are always alphabets, and the following characters are mostly numbers. (eg. ab123c or xy5678)

How can I check in the input field with jquery / javascript that user only enters in above format before hitting submit.

<input type="text" maxlength="6" name="uid" id="uid" placeholder="enter user id here">
tx-911
  • 427
  • 1
  • 4
  • 17
  • 2
    What is the problem with your code? Have you tried any pattern yet? – Wiktor Stribiżew Apr 25 '18 at 20:20
  • 1
    What do you mean by "mostly numbers"? Does there have to be more numbers than letters in that part? – Barmar Apr 25 '18 at 20:52
  • And why is it *generally* 6 characters long? Can it be shorter or longer sometimes? Is there a rule for when this is allowed? – Barmar Apr 25 '18 at 20:53
  • @Barmar always 6 – tx-911 Apr 25 '18 at 20:54
  • 1
    Please edit your question to describe the rules more precisely, without all these vague qualifications. – Barmar Apr 25 '18 at 20:55
  • In your example, you say "mostly numbers" and then provide an example where there's an alpha character `ab123c`. Is there some importance to validating the last 4 digits? (Say, must contain at least one number.) – wahwahwah Apr 25 '18 at 21:46

3 Answers3

4

You can validate your input using regex

regex = /^[a-z]{2}[a-z0-9]{4}$/i ;

regex = /^[a-z]{2}[a-z0-9]{4}$/i ;

console.log('ab1234', regex.test('ab1234'));
console.log('abc234', regex.test('abc234'));
console.log('ab1d34', regex.test('ab1d34'));
console.log('ab12e4', regex.test('ab12e4'));
console.log('ab12yz', regex.test('ab12yz'));
console.log('2b1234', regex.test('2b1234'));
console.log('a11234', regex.test('a11234'));
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
2

You don't need javascript or jquery. Can use HTML. w3c School

<input type="text" maxlength="6" name="uid" id="uid" placeholder="enter user id here" pattern="[a-zA-z]{2}[a-zA-Z0-9]{4}">

Thanks for the update Barmar, not used it before.

Update:

First I don't know why this is closed. The question isn't about learning regular expression, it's about implementation. Aurelien provides the right answer if you want to use jQuery, mine is if you don't want to use jQuery or javascript. Zohaib ljaz doesn't address the core issue of implementation.

Second: Most of the comments aren't helpful, he does provided examples and it has max-length in the code so of course 6 is the max.

1

Try this

$('form').on('submit', function(e){
    e.preventDefault();
    if($('#uid').val().match(/^[a-zA-Z]{2}[a-zA-Z0-9]{4}$/)){
        $(this).submit()
    }
    else {
     //Do your error logic here
    }
}
Aurelien
  • 1,497
  • 7
  • 15