Reputation: 1161
I never used javascript in rails, and i have pretty basic questions about this matter. This is what i want to implement in my application:
"In my application, when a user is being created, s/he can select their birthdate by choosing a year, a month, and a day in three different drop-downs. Presently, the user is able to choose a future date as his birth date. I'm in need a way to check if the user is selecting a valid date and warn them in the event the date is invalid."
I would like to know what am i doing wrong. Thanks anyway!
In view (form):
<div class="control-group">
<%= f.label "Date of Birth (YYYY-MM-DD)", :class => 'control-label' %>
<div class="controls">
<%= f.select :year_Of_Birth , options_for_select((Time.now.year - 100)..(Time.zone.now.year )), :include_blank => true, :id => "year",:onchange => 'validDate()'%>
<%= f.select :month_Of_Birth, 1..12 , :include_blank=> true, :onchange => 'validDate()', :id => "month" %>
<%= f.select :day_Of_Birth, 1..31 , :include_blank => true, :onchange => 'validDate()', :id => "day" %>
</div>
</div>
In my application.js:
function validDate(){
var y = document.getElementById("year").value;
var m = document.getElementById("month").value;
var d = document.getElementById("day").value;
if(m==2 && leapYear(y)==false && d>28)
document.write("Invalid Date.");
if(m==2 && leapYear(y)==true&& d>29)
document.write("Invalid Date.");
if(m==4 && d>30)
document.write("Invalid Date.");
if(m==6 && d>30)
document.write("Invalid Date.");
if(m==8 && d>30)
document.write("Invalid Date.");
if(m==9 && d>30)
document.write("Invalid Date.");
if(m==11 && d>30)
document.write("Invalid Date.");
}
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
Upvotes: 0
Views: 106
Reputation: 589
You could use the JavaScript's Date
var y = document.getElementById("year").value;
var m = document.getElementById("month").value;
var d = document.getElementById("day").value;
// selected date, the month has index of 0
var selectedDate = new Date(y, m - 1, d);
// first day of next month
var maxAllowedDateForMonth = new Date(y, m, 1);
// date now to check for future dates
var now = new Date;
if (selectedDate < maxAllowedDateForMonth && selectedDate < now)
{
document.write("Invalid Date.");
}
Upvotes: 1