Javascript getting the Leap Year - javascript

I need help with my code. I need to call my function leapYear() to my FieldValidator() function to determine if the year given by the user is leap year or not.
Here is my code:
function FieldValidator() {
var err = "";
var valid = false;
var leap = new leapYear(year)
//year
if(document.getElementById('year').value == ""){
valid = true;
err += "Enter year \n";
document.getElementById('year').style.borderColor = "red";
}
else if(document.getElementById('year').value < 1000 || document.getElementById('year').value > 9999){
valid = true;
err += "Invalid Year \n";
document.getElementById('year').style.borderColor = "red";
}
else {
document.getElementById('year').style.borderColor = "green";
}
//month
if(document.getElementById('month').value == ""){
valid = true;
err += "Enter Month \n";
document.getElementById('month').style.borderColor = "red";
}
else if(document.getElementById('month').value < 1 || document.getElementById('month').value > 12){
valid = true;
err += "Invalid Month\n";
document.getElementById('month').style.borderColor = "red";
}
else {
document.getElementById('month').style.borderColor = "green";
}
//day
if(document.getElementById('day').value == ""){
valid = true;
err += "Enter day \n";
document.getElementById('day').style.borderColor = "red";
}
else if (document.getElementById('month').value == 2) {
if(document.getElementById('year').value == leap()) {
if(document.getElementById('day').value > 29) {
valid = true;
err += "invalid leap\n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
else if(document.getElementById('year').value != leap()) {
if(document.getElementById('day').value > 28) {
valid = true;
err += "invalid \n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
}
else if (document.getElementById('month').value != 2) {
if(document.getElementById('day').value < 1 || document.getElementById('day').value > 31 ) {
valid = true;
err += "Invalid day \n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
else {
document.getElementById('day').style.borderColor = "green";
}
if(valid){
alert(err)
return false;
}
return true;
}
function leapYear(year)
{
return ((document.getElementById('year').value % 4 == 0) && (document.getElementById('year').value % 100 != 0)) || (document.getElementById('year').value % 400 == 0);
}

For anything time related, I'm using momentjs (either like you in the browser or on the server in nodejs).
It's as simple as this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
var year = 2015;
moment([year]).isLeapYear(); // false
</script>
The isLeapYear function itself is quit simple, too. So you can use that to determine if the year is a leap year or not.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
Source

Related

How do i randomize a quiz in javascript while recording right and wrong answers?

I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}

Code which give me error message but not clearing the error message after entering field

Code which give me error message but not clearing the error message after entering field :
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
}
function check(form) {
flag = 0;
otpValidate();
if (flag == 1)
return false;
else
return true;
}
Just add an empty message in your main function. Then call a keyup function to call your main function. try something like:
function otpValidate() {
var otp = oneTimePass.onetimepass.value.trim();
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
flag = 0;
}
}
var otp = oneTimePass.onetimepass;
otp.addEventListener("keyup", otpValidate);
Optimized way
function otpValidate() {
otp = oneTimePass.onetimepass.value.trim();
document.getElementById('error0').innerHTML = "";
flag = 0;
if(!otp) {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
return flag;
}
function check(form) {
var flag = otpValidate();
if (flag == 1)
return false;
return true;
}
First of all fix the codes here
function check(form) {
//flag = 0; This will make no sense to check it
otpValidate();
if (flag == 1)
{
flag = 0;
return false;
}
else
return true;
}
And for the problem you are facing
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
}
}
Try like this
var flag = 0;
function otpValidate() {
otp = oneTimePass.onetimepass.value;
if(otp == "") {
document.getElementById('error0').innerHTML = "Enter one time password";
flag = 1;
} else if(otp.length != 6) {
document.getElementById('error0').innerHTML = "PIN must be 6 digits";
flag = 1;
}
else {
document.getElementById('error0').innerHTML = "";
flag = 0;
}
}
function check(form) {
otpValidate();
if (flag == 1)
return false;
else
return true;
}

Javascript Focus

I am using this script for i need a focus on every alert.i tried many ways but it is not working.
script:
function validateTime(obj) {
var timeValue = obj.value;
if(timeValue == "" || timeValue.indexOf(":") < 0) {
alert("Invalid Time format");
obj.value = "";
return false;
} else {
var sHours = timeValue.split(':')[0];
var sMinutes = timeValue.split(':')[1];
if(sHours == "" || isNaN(sHours) || parseInt(sHours) > 23) {
alert("Invalid Time format");
obj.value = "";
return false;
} else if(parseInt(sHours) == 0) sHours = "00";
else if(sHours < 10) sHours = "0" + sHours;
if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes) > 59) {
alert("Invalid Time format");
return false;
} else if(parseInt(sMinutes) == 0) sMinutes = "00";
else if(sMinutes < 10) sMinutes = "0" + sMinutes;
obj.value = sHours + ":" + sMinutes;
}
return true;
}
aspx:
<asp:TextBox ID="lblMonday" CssClass="lblMonday" runat="server" Width="55px" onchange="validateTime(this);"></asp:TextBox>
You just need to call obj.focus() after each alert. As in:
alert("Invalid Time format");
obj.value = "";
obj.focus();
You probably haven't called the focus() method on the text element. Also it is not a good practice to mix presentation and functionality. You must not use the onchange attribute in the HTML markup.
document.getElementById("lblMonday").onchange = function() {
if(!validateTime(this)) { this.focus(); }
}
You can remove much of the duplication by calling alert() and resetting the field's value in a single place, as in
document.getElementById("lblMonday").onchange = function() {
if(!validateTime(this)) {
this.focus();
this.value="";
alert("Invalid time format");
}
else {
//Do something else
}
}

Javascript code to convert serial numbers converted from PHP

These two Javascript functions are supposed to convert serial numbers (2-9999) for example into a number , but the functions below are not working for some reason .. they were originally written in PHP ... Works in PHP but not for Javascript.
<html>
<head>
<script type="text/javascript">
function my_isnum(str, negative=false, decimal=false)
{
var has_decimal = false;
var len = strlen(str);
if (len > 0) {
var valid = true;
for (var i=0; valid && i < len; i++) {
if (!(str[i] >= "0" && str[i] <= "9")) {
if (str[i] == "-") {
if (!negative || i != 0) {
valid = false;
}
} else if (str[i] == ".") {
if (!decimal || has_decimal) {
valid = false;
}
} else {
valid = false;
}
}
}
} else {
valid = false;
}
return valid;
}
function esn_to_num(esn) {
var tmp = [];
if ((tmp = esn.split("-")) {
if (tmp.length == 2
&& my_isnum(tmp[0])
&& my_isnum(tmp[1])
) {
esn = ((tmp[0] << 23) | tmp[1]);
} else {
esn = -1;
}
} else {
esn = -1;
}
return esn;
}
alert(2-9999);
</script> </head>
</html>
Original PHP functions
<?php
function my_isnum($str, $negative=false, $decimal=false)
{
$has_decimal = false;
$len = strlen($str);
if ($len > 0) {
$valid = true;
for ($i=0; $valid && $i<$len; $i++) {
if (!($str[$i] >= '0' && $str[$i] <= '9')) {
if ($str[$i] == '-') {
if (!$negative || $i != 0) {
$valid = false;
}
} else if ($str[$i] == '.') {
if (!$decimal || $has_decimal) {
$valid = false;
}
} else {
$valid = false;
}
}
}
} else {
$valid = false;
}
return $valid;
}
function esn_to_num($esn)
{
if (($tmp = explode('-', $esn))) {
if (sizeof($tmp) == 2
&& my_isnum($tmp[0])
&& my_isnum($tmp[1])
) {
$esn = (($tmp[0] << 23) | $tmp[1]);
} else {
$esn = -1;
}
} else {
$esn = -1;
}
return $esn;
}
?>
There is no such thing as strlen in Javascript. Use str.length instead.
Also, as Jason Sperske suggested below, change this:
function my_isnum(str, negative=false, decimal=false)
To this:
function my_isnum(str, negative, decimal)
{
if (typeof negative == "undefined") negative = false;
if (typeof decimal == "undefined") decimal = false;
....
}
These two javascript functions are supposed to convert serial numbers (2-9999) for example into a number.
Why not just get rid of the - and parse as a decimal number?
function padToFourDigits(_, digits) {
return "0000".substring(digits.length) + digits;
}
function serialToNum(serialNumStr) {
return +(serialNumStr.replace(/-(\d{1,4})/g, padToFourDigits));
}
Then
serialToNum('2-9999') === 29999
serialToNum('2-999') === 20999

Date Validation not working using JavaScript

I have two two date fields - from date and to date, and i need to validate 3 things
Both the values are entered or not
Date datatype check
To date must be greater than from date.
But my script is not working.
can some body please check?
Thanks
function checkBothDates(sender,args)
{
var from = document.getElementById(sender.From);
var to = document.getElementById(sender.To);
var behaviorId = sender.behavior;
var from_value = from.value;
var to_value = to.value;
if((from_value == "")&&(to_value == ""))
{
args.IsValid = true;
}
else
{
if((from_value != "")&&(to_value != ""))
{
if((isValidDate(from_value))&&(isValidDate(to_value)))
{
if(from_value < to_value)
{
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please enter valid dates in both the fields";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please make sure you enter both the values";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
}
function isValidDate(val)
{
var format = 'dd/MM/yyyy'
var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!regexp.test(val))
{
return false;
}
else
{
try
{
$.datepicker.parseDate(format,val,null);
return true;
}
catch(Error)
{
return false;
}
}
}
Your code is pretty repetitive, you can shorten a lot of it.
Also note that the regex check is entirely unnecessary, since $.datepicker.parseDate() won't accept anything invalid anyway.
function checkBothDates(sender, args) {
var from = parseDate( $(sender.From).val() ),
to = parseDate( $(sender.To).val() );
args.IsValid = false;
if (from == "" && to == "" || from && to && from <= to) {
args.IsValid = true;
} else if (from == null || to == null) {
sender.errormessage = "Please enter valid dates in both the fields";
} else if (from > to) {
sender.errormessage = "To date must be greater than or equal to the from date";
} else {
sender.errormessage = "Please make sure you enter both the values";
}
if (!args.IsValid && sender.behavior) {
openCollapsiblePanel(sender.behavior);
}
}
function parseDate(val) {
if (val == "") return "";
try {
return $.datepicker.parseDate('dd/MM/yyyy', val);
} catch (ex) {
return null;
}
}
There is a problem in your code aroun the 19th line. You wrote:
if(from_value < to_value) {
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
But you definitely want that from_value is smaller then to_value. Fix it!

Categories