kalenpw kalenpw - 1 year ago 64
Javascript Question

Javascript validate string is a character followed by numbers

I am trying to validate a string where the first character must be an

and the remaining characters must be numerical. For example:

x1234 == true;
k1234 == false;
x12k4 == false;
1x123 == false;

Here is my code:

function isValidCode(code){
var firstLetter = code.substring(0,1);
var remainingCode = code.substring(1);
var validCode = false;

// Debugging

if(firstLetter == 'x'){
validCode = true;
validCode = true;

I've debugged my
function, so I'm 99.9% sure the issue isn't there, but here it is just in case:

function isNumeric(numberIn)
var returnValue = true;

if (isNaN(numberIn) || isNaN(parseInt(numberIn, 10)))
returnValue = false;

return returnValue;

I've tried several things such as reversing my logic where I start with the given condidtion being true and then checking
if(!(firstLetter == 'x'))
I've tried
and I've tried casting the remaining portion of the code with
and not casting it at all, but none of these seeem to do the trick. The console does log the proper first character and remaining characters in the code so I'm not sure what is wrong.

Answer Source

You can use a regular expression test:

function isValidCode(code) {
    return /^[a-z]\d+$/.test(code);

I am making an assumption that a lower case letter is required, followed by at least one digit.

To match only only the letter 'x', use:

function isValidCode(code) {
    return /^x\d+$/.test(code);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download