'Checking if the first character of a string is a number gives an error that charat is not a valid method
I have a method that validates a field against 3 regex expressions and returns an error based on which expression failed.
function mfpValidateValue()
{
var pCtrl = window.document.forms[0].txtValue;
var pStrValue = mTrim(pCtrl.value);
if (pStrValue == '')
return true;
var regexNum = new RegExp("^[0-9]{9}.{0,3}$"); // First 9 are numeric followed by up to any 3 characters
var regexLetter1 = new RegExp("^[A-Z]{1,3}[0-9]{6}$"); //Up to the first 3 are alpha, then there are exactly 6 numbers
var regexLetter2 = new RegExp("^[A-Z]{1,3}[0-9]{9}$"); //Up to the first 3 are alpha, then there are exactly 9 numbers
var error = "";
// If any of the RegEx fails, set base error message
if (!regexNum.test(pStrValue) || !regexLetter1.test(pStrValue) || !regexLetter2.test(pStrValue))
error = "Please enter a valid Value.";
// Set more specific error message.
if (!isNaN(pStrValue.charat(0)))
error += " If the first character of Value is a digit, then the first nine characters must be digits.";
else
error += " If the first character of Value is a letter, up to the first three characters must be letters proceeded by 6 or 9 digits.";
return (error == "");
}
I get the following error message on this line:
if (!isNaN(pStrValue.charat(0)))
Object doesn't support property or method 'charat'
And the value in pStrValue is:
"12345678"
Is JavaScript using the term "object" ambiguously here to refer to my particular variable, or does it actually think pStrValue is an object and not a string?
Solution 1:[1]
You check this:
if not is Not a Number
The new ECMAScript 2015 (ES6) has a new method:
Number.isInteger(value)
Mozilla Developer Network describes:
If the target value is an integer, return true, otherwise return false. If the value is NaN or infinite, return false.
See full information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
A proper alternative is:
if (Number.isInteger(parseInt(pStrValue.charAt(0))))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
