0

This is the client script function for an asp.net validation control.

<script type="text/javascript">
    function validateDateControl(sender, args) {

        var d = new Date(args.Value);

        args.IsValid = (Object.prototype.toString.call(d) === "[object Date]");

        if (!args.IsValid) {
            sender.innerText = "Client: Invalid date";
        }     

        return args.IsValid;
    }
</script>

Immediate Window Results:
d
NaN
Object.prototype.toString.call(d) === "[object Date]"
true

Why is the comparison evaluating True?

2
  • I cannot understad your question. Please, post more details. Sorry :) Commented Feb 16, 2012 at 15:18
  • 3
    An invalid date is still a date object, it just can't be represented properly. Commented Feb 16, 2012 at 15:18

2 Answers 2

8

Because new Date('as;dlas;ld,as;dl,as') is still a Date object.

> var d = new Date('as;dlas;ld,as;dl,as')
  undefined
> d.toString()
  "Invalid Date"
> Object.prototype.toString.call(d)
  "[object Date]"

A better way to check date validity is to see that Date.getTime() does not return NaN:

function validateDateControl(sender, args) {

    var d = new Date(args.Value);

    args.IsValid = !isNaN(d.getTime());

    if (!args.IsValid) {
        sender.innerText = "Client: Invalid date";
    }     

    return args.IsValid;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Because it's an object of type Date but the value (what is shown in string representation of the object itself, not the type) is invalid.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.