Hi,
I am new in phpmysql development.I have stuck in problem.
I want to validate user date of birth (only year) using if else if through javascript.
1- if user left it empty then i want it to show message "fill this".
2-else if user's age is less then 20 it will show "not enough".
3-else "welcome".
But if field is empty it show welcome message. please help me in this regard.
Thanks so much.
<html>
<head>
<title>
This is dob validation
</title>
<script language="javascript">
function dobvali()
{
var currentdate=new Date();
var yearonly=currentdate.getFullYear();
var usrdob=document.getElementById('dob').value;
var res=yearonly-usrdob;
if(res20)
{
alert('not enough');
}
else
{
alert('welcome');
}
}
</script>
</head>
<body>
Enter DOB (YYYY):<input type="text" id="dob"/>
<input type="button" value="check" onClick="dobvali();"/>
</body>
</html>
You should check if usrdob is empty or not a number:
Code:
function dobvali(){
var currentdate = new Date();
var yearonly = currentdate.getFullYear();
var usrdob = document.getElementById('dob').value;
var res = yearonly-usrdob;
if (!usrdob || isNaN(usrdob))
{
alert('fill this');
}
else if (res < 20)
{
alert('not enough');
}
else
{
alert('welcome');
}
}
ok brother thanks so much for your reply, but there is an other confusion.
According to my understanding the logic that you have used in if else if statement is that ,when a user incomplete year or left the field empty it gives error message "fill this", but if i enter 19 or 198 that is incomplete value it show message "Welcome". That makes me confused please explain it.
Thanks.
<html>
<head>
<title>
This is dob validation
</title>
<script type="text/javascript">
function dobvali(){
var currentdate = new Date();
var yearonly = currentdate.getFullYear();
var usrdob = document.getElementById('dob').value;
var res = yearonly-usrdob;
if (!usrdob || isNaN(usrdob))
{
alert('fill this');
}
else if (res < 20)
{
alert('not enough');
}
else
{
alert('welcome');
}
}
</script>
</head>
<body>
Enter DOB (DD/MM/YYYY):<input type="text" id="dob" maxlength="10"/>
<input type="button" value="check" onClick="dobvali()"/>
</body>
</html>
Well, if you say it like that then it is a bit confusing. lol
It would probably be better to add more different checks with different messages.
Code:
function dobvali()
{
var currentdate = new Date();
var yearonly = currentdate.getFullYear();
var usrdob = document.getElementById('dob').value;
var res = yearonly-usrdob;
if (!usrdob) // if the input is empty
alert('fill this');
else if (isNaN(usrdob)) // if the input does not contain a number
alert('invalid input');
else if (usrdob < yearonly-100 || usrdob > yearonly) // if date of birth is in the future or more than 100 years ago
alert('invalid year');
else if (res < 20) // if age is less than 20
alert('not enough');
else
alert('welcome');
}
Bookmarks