1

I want to restrict the user to enter in textbox only string followed by number only for e.g

AA1->true
AA1A->False
AA12->True
AB12AA14AB->false
12AA->false
ABC12->false
AA->false

So please let me know how can I add validation for above condition/cases using javascript.

4
  • 1
    Do you want to know how to validate this, or do you want to get an idea how js code can know if the input is valid? Commented Aug 17, 2018 at 6:51
  • learn about regex in jquery or javascrit.. it will help you more Commented Aug 17, 2018 at 6:52
  • validate by regex is what you need. try [A-Z]+[0-9]+ for example Commented Aug 17, 2018 at 6:52
  • ABC12 is a alphabetical characters followed by numeric characters, shouldn't it be true as well? Commented Aug 17, 2018 at 6:53

3 Answers 3

2

Use a regular expression:

const validate = str => /^[A-Z]+\d+$/.test(str);
`AA1
AA1A
AA12
AB12AA14AB
12AA
ABC12
AA`
  .split('\n')
  .forEach(str => console.log(validate(str)));

^ indicates the start of the string, [A-Z]+ matches one or more uppercase alphabetical characters, \d+ matches one or more numbers, and $ matches the end of the string.

Sign up to request clarification or add additional context in comments.

Comments

1

function isStrEndWithNum(str){ if(str) return !isNaN(str[str.length-1]); return false; }

Comments

0

You can use the .test function which is present in JavaScript

/^([\w]+[0-9])$/.test('YourStringHere');

i am just confused with second last condition of yours.

Other than that all your conditions are passed with the above code.

3 Comments

my second last condition is don’t allow consecutive alphabets followed by number like ABC12
Using above code if I enter in textbox like 'aa1212dd12' it allows.In my case it don't allow.Only aa12,BB45 allow.
Sorry for the Late reply but i think this will resolve the issue /^([A-Z]{1})(\d{1})|([A-Z]{1})(\d{2})|([A-Z]{2})(\d{1})|([A-Z]{2})(\d{2})|([A-Z]{3})(\d{1})$/.test("Your String Here")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.