# Is my approach for validating character after number good enough

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`, `B12` `A2` 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.

I do not see any check that the first character is in A-Z and you do also not check on number > 12

My quick solution

``````If(x.length > 1 && x.length < 4)
{
const letter = x.charCodeAt(0);
const number = parseInt(x.substring(1));
If(letter >= 65 && letter <=90 && !isNaN(number) && number >= 1 && number  <= 12)
return true;
}
return false
``````
1 Like

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 `A12` `A11` etc.

Sorry my fault. CharAt is returning char not char code. I have updated my answer

1 Like

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
``````

https://regex101.com/r/GLC8QC/2

This could also be used in your input as a pattern

``````<input
type='text'
id='starting-well-id'
name='starting_well_id'
pattern='^[A-Z](?:[1-9]|1[0-2])\$'
>
``````

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.

2 Likes

Thanks. Those error messages that’s popping up as user types, are you making use of any library?

No, it is built into the browser.

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.