0

I got this script

 $("#SocialSecurityNumber").attr("placeholder","YYYY-MM-DD-XXXX").blur(function () {
        var str = $('#SocialSecurityNumber').val();
        var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
        var todays_date = new Date();
        var birth_date = new Date(res[1], res[2], res[3]);

        if (todays_date - birth_date > 565633905872) {
            $("#btn-activation").removeAttr('disabled');
            $("#SocialSecurityNumber").removeClass("input-validation-error");
        } else {
            $("#SocialSecurityNumber").attr("placeholder","Please enter date of birth as YYYY-MM-DD-XXXX").addClass("input-validation-error");
            $("#btn-activation").attr("disabled", "disabled");
        }
    });

});

Which will validate age, from input #SocialSecurityNumber However, when entering letters or other jibberish it doesnt validate at all and i get js error

Uncaught TypeError: Cannot read property '1' of null 

Could somone help me with how i can add so this script also validates incorrect characters? (when regex is not matched)

rac
  • 263
  • 2
  • 7
  • 13
  • If the RegEx doesn't match, `res` will be null... so calling the index on it will always fail. You need to test for `res != null` (or similar) before doing `res[1]` – freefaller Feb 26 '14 at 11:48

2 Answers2

1

As per my comment, in javascript, if the RegEx does not match, then the result is null.

Therefore you are attempting to index a null variable... which is why you're seeing the error.

You need to check for a null value, with something like this...

 var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
 var todays_date = new Date();
 var birth_date = null;
 if (res != null) {
   birth_date = new Date(res[1], res[2], res[3]);
 }

 if (birth_date == null || todays_date - birth_date > 565633905872) {
    ...

You'll need to sort out the exact logic yourself, but hopefully this gives you an idea of what is going wrong.

freefaller
  • 19,368
  • 7
  • 57
  • 87
0

If there is no match, then res will be null. So one thing which you can do is:

if(res.length==3)
var birth_date = new Date(res[1], res[2], res[3]);

This confirms that you get only right number of matches.

Aashray
  • 2,753
  • 16
  • 22