I have the following function where I’m using regex matching to check for proper date format when a change event happens on the value in the input field.
My problem is that month, day, and year are returning as NaN and I’m not sure why. I’m parsing regex objects [1], [2], and [3] respectively with parseInt() so I’m not sure why they are returning as NaN.
validateDate: function(event) {
var input = $(event.target);
var enteredDate = input.val();
input.destroyValidationMessage();
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var result = pattern.test(enteredDate);
if (result !== null) {
var month = parseInt(result[1], 10);
var day = parseInt(result[2], 10);
var year = parseInt(result[3], 10);
}
}
.test()[MDN] returns a boolean, i.e.trueorfalseand only tells you whether the expression matches the input or not.Then, since
if(result !== null)is always true forresultbeing eithertrueorfalse, theifstatement block is executed.match[x]is the same astrue[x](orfalse[x]) and instead of throwing an error, it returnsundefined. This is because JavaScript converts the primitive value to an object internally and accessing a non-existing property results in the return valueundefined.Furthermore,
parseInt(undefined, 10)returnsNaN.You want to use
.match()[MDN]:A shorter way of converting a numerical string to a number is using the unary
+operator:which gives you the same result here since the input string only contains digits.