Just wanted to get your opinion about whether my approach of validating following scenario is good?
I want to make sure that that the first character is aways a letter from A-Z and the character following the letter will always be a number from 1-12 So my input can only be like A1, B12A2 etc.
Can you take a look at this JSFiddle and see if I’m heading in right direction? I should probably check for charAt(2) as well to address two digits number after letter but wanted to check first if overall approach is looking good.
Thanks. I tested your solution by plugging in this JSFiddle with some if else loop adjustments, could you tell me why it is always returning false? I always see console.log("NOT good"); printing even with valid values like A12A11 etc.
No problem. Forgot to mention one requirement where the charAt(0) should always be a letter and then followed by number at charAt(1) or charAt(2) depending upon if it’s a one-digit number or two. Basically, it is always going to be like A1 or A12 etc It can’t be 12A or 1B etc.
In order to address this, I’m wondering if it’s already addressed using this line if(letter >= 65 && letter <= 90 && !isNaN(number) && number >= 1 && number <= 12){ or do I need to add another check by checking if charAt(0) is in the range of 65-90 ?
So starts with a capital letter A-Z then a number from 1-12?
Doing a quick test this regex might be another option.
^[A-Z](?:[1-9]|1[0-2])$
^ starts of line
[A-Z] capital letter A to Z
(?: start of a group (non-capturing)
[1-9] 1 to 9
| or
1[0-2] 1 followed by 0 to 2
) end of group
$ end of line
Here is an example. Inputting an invalid code and clicking on the button will trigger the browsers built in validation and a message asking for a valid input.
Note: this sort of validation can be tampered with through the browser dev tools. So for instance in chrome, I could go into Elements and edit the html code.
If it is going to the backend it would need to be properly validated.