kalenpw kalenpw - 2 months ago 6
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

'x'
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
console.log(firstLetter);
console.log(remainingCode);

if(firstLetter == 'x'){
validCode = true;
}
if(isNumeric(Number(remainingCode))){
validCode = true;
}
}


I've debugged my
isNumeric()
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
===
and I've tried casting the remaining portion of the code with
Number()
,
+()
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

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);
}
Comments