views:

27

answers:

2

I am working with the script that will be checking the age from the current date and very simple logic that is by taking year input. Here is the code:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Date Check</title>
<script language="javascript" type="text/javascript">
function check()
{
    var curtime = new Date;
    var curyear = curtime.getFullYear();
    var inpyear = document.getElementById('txtdate').value;
    if(inpyear.length == 4)
    {
        var result = curyear - inpyear;
        if(result >= 18 || result <= 100)
        {
            alert('Welcome');
        }
        else
        {
            alert('Your Too Much Old or Young to see the Site');
        }
    }
    else
    {
        alert('Please Put the  4 Digit Year Example : 1987');
    }

}
</script>
</head>

<body>
Enter Year: <input type="text" id="txtdate" />
<input type="button" onclick="check();" value="Check" />
</body>
</html>

The Problem is if I enter even 1999 which is less then 18 but still it is giving the message of welcome but it should not true the condition of if because I allowed the range from 18-100. Is there any type error or what is the error ?

+1  A: 

result >= 18 || result <100 will always be true. You have to use &&

Gabi Purcaru
Thanks yea Lol my bad i missed a Little Logic :D
PhpSeeker
+2  A: 
if(result >= 18 && result <= 100)
    {
        alert('Welcome');
    }

result >= 18 || result <= 100 will always be true.

N 1.1
It will be always `true`... unless the value of `result` is `NaN`. (Which might seem odd but it's also a `Number` value). `typeof NaN == 'number'` :)
CMS
@CMS: ya. but for that to happen, `inpyear` must be `NaN` in which case the outer `if` will fail. :)
N 1.1
Thanks lots of I missed a little logic :">!!
PhpSeeker
@PhpSeek no prob
N 1.1
@N1.1, `inpyear` is input from the user, the outer `if` only checks the `length` prop. to be `4`, for example, if the user types `"foos"`, we will get `NaN`: `isNaN(2010 - "foos")`. Anyway it was just a random thought. :P
CMS
@CMS: quite right :). Anyways, OP should check against NaN.
N 1.1
@CMS well for that we can use simple Regular Expression i done it with var alphaExp = /^[0-9]+$/; and then match its value with the inpyear :) its simple :)
PhpSeeker