Ensuring date can be added in past - javascript

What can I do to this piece of code to ensure that it can allow absences to be added in the past as well as the future? Whenever I attempt to add anything in the past, it is appears to want to still give me the error that I cannot add an absence in the past. I'm not even sure how to code to ensure it can, or which bit to delete. I'm aware there is a bit of code that is not allowing me to, but I'm not sure which bit and what to delete. I am not extremely skilled at JavaScript but it is in my project and I am unsure what to do with it.
dateValid: function () {
var s = $(this).val();
if ($(this).required()) {
var date = new Date(s);
if (!isNaN(date)) {
if (date >= Date.parse(new Date().toDateString())) {
$(this).removeClass("error");
return true;
}
else {
validation.showError("Past", $(this).attr("name"));
$(this).addClass("error");
return false;
}
}
else {
validation.showError("Invalid", $(this).attr("name"));
$(this).addClass("error");
return false;
}
}
else return false;
},
dateRangeValid: function (toDate) {
var s = $(this).val();
if ($(this).required()) {
if (toDate.required()) {
var dateFrom = new Date(s);
var dateTo = new Date(toDate.val());
if (!isNaN(dateFrom) && !isNaN(dateTo)) {
if (dateTo >= dateFrom) {
if (dateFrom >= Date.parse(new Date().toDateString())) {
$(this).removeClass("error");
toDate.removeClass("error");
return true;
}
else {
validation.showError("Past", "date");
$(this).addClass("error");
toDate.addClass("error");
return false;
}
}
else {
validation.showError("Invalid", "date");
$(this).addClass("error");
toDate.addClass("error");
return false;
}
}
else {
validation.showError("Invalid", "date");
$(this).addClass("error");
toDate.addClass("error");
return false;
}
}
else {
validation.showError("Required", "dateTo");
$(this).addClass("error");
toDate.addClass("error");
return false;
}
}
else {
validation.showError("Required", "dateFrom");
$(this).addClass("error");
toDate.addClass("error");
return false;
}
},

Here's your error:
if (dateTo >= dateFrom) {
// This if statement checks if dateFrom is today or later!!
if (dateFrom >= Date.parse(new Date().toDateString())) {
$(this).removeClass("error");
toDate.removeClass("error");
return true;
}
else {
validation.showError("Past", "date");
$(this).addClass("error");
toDate.addClass("error");
return false;
}
}
Replace with
if (dateTo >= dateFrom) {
$(this).removeClass("error");
toDate.removeClass("error");
return true;
}
and there should no longer be a problem.

Related

How to check if 2 strings are equal in JavaScript?

I'm a beginner in JS and trying to sort some cars by their model. The models are sorted by ranking in this order (Mercedes, BMW, Jeep, Nissan). I would like it to be case-insensitive. I went about it by creating a variable for creating the desired rankings.
var modelRanking = function(car) {
if (car.model.toLowerCase() === 'mercedes') {
return 1;
} else if (car.model.toLowerCase() === 'bmw') {
return 2;
} else if (car.model.toLowerCase() === 'jeep') {
return 3;
} else if (car.model.toLowerCase() === 'nissan') {
return 4;
} else {
return 5;
}
}
function modelComparator(car1, car2) {
if (car1.modelRanking < car2.modelRanking) {
return true;
} else if (car1.modelRanking > car2.modelRanking) {
return false;
} else if (car1.modelRanking == car2.modelRanking) {
return yearComparator(car1, car2);
}
}
However the modelRanking is always returning 5.
Instead of car1.modelRanking, use modelRanking(car1) because modelRanking is a function in global scope, not a property of car1.
function modelComparator(car1, car2) {
if (modelRanking(car1) < modelRanking(car2)) {
return true;
} else if (modelRanking(car1) > modelRanking(car2)) {
return false;
} else if (modelRanking(car1) == modelRanking(car2)) {
return yearComparator(car1, car2);
}
}

parameter.includes() is not a function

I'm pretty new at js programming. I'm developing an admission form as part of our project to be submitted. It's also my first time asking a question here.
I'm creating a form of validation to prevent any invalid values to be entered. I also need some optimizations at my code. If you have any suggestions to make it shorter, I'll be glad to accept your suggestion too.
I tried executing the matchCheck() function on other scenarios, but it just works fine. I also tried executing validateDate() on the console and other scenarios, but it also worked without any errors. I got an error when the functions are executed at if statements.
Here is the error message: Unknown TypeError: arrayToBeChecked.includes is not a function
I got an error at these function and if statements:
function matchCheck(arrayToBeChecked, findingValue) {
return arrayToBeChecked.includes(findingValue);
}
if (matchCheck(date[0], "null") === false)
if (validateDate(bdate) === true)
Here is the code (Excluded some of the unrelated variables and codes):
//Check Match
function matchCheck(arrayToBeChecked, findingValue) {
return arrayToBeChecked.includes(findingValue);
}
//Date Validator
//Expected Format [MM/DD/YYYY]
function validateDate(date) {
//check if the date is valid
var leapYear = date[2] % 4;
var mos31 = ["1", "3", "5", "7", "8", "10", "12"];
var mos30 = ["4", "6", "9", "11"];
var flyInv = ["30", "31"];
var fnlyInv = ["29", "30", "31"];
var mos30Inv = "31";
if (matchCheck(date[0], "null") === false) {
if (matchCheck(date[1], "null") === false) {
if (matchCheck(date[2], "null") === false) {
if (leapYear == 0) {
if (date[0] == "2") {
if (matchCheck(flyInv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else if (matchCheck(mos31, date[0]) === true) {
return true;
}
else if (matchCheck(mos30, date[0]) === true) {
if (matchCheck(mos30Inv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else {
return false
}
}
else {
if (date[0] == "2") {
if (matchCheck(fnlyInv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else if (matchCheck(mos31, date[0]) === true) {
return true;
}
else if (matchCheck(mos30, date[0]) === true) {
if (matchCheck(mos30Inv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
//Contact Number Validator
//Expected Format [09XXXXXXXXX]
function cnValid(nos) {
if (nos.value.length === 11) {
if(nos.indexOf("09") > -1) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
//Check for empty selects
function checkEmptySelects(el) {
var selects = document.querySelectorAll(el);
var i;
for (i = 0; i < selects.length; i++) {
if (selects[i].value == "0") {
return true;
}
else {
return false;
}
}
}
//Valid Relation Values
var vrv = ["mother", "father", "grandmother", "grandfather", "auntie", "uncle", "housemaid", "Mother", "Father", "Grandmother", "Grandfather", "Auntie", "Uncle", "Housemaid", "Aunt", "aunt", "brother", "Brother", "sister", "Sister", "cousin", "Cousin"];
//Start Review
function reviewForm() {
var letters = /^[a-zA-Z\s]*$/;
var mailFormat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var noScFormat = /[^a-zA-Z0-9\\,\\.\s]/g;
//Perform Checks
if (checkEmptySelects("select") === false) {
if (ln.value.match(letters)) {
if (fn.value.match(letters)) {
if (mn.value.match(letters)) {
if (eml.value.match(mailFormat)) {
if (age.value >= 0) {
if (age.value <= 100) {
if (validateDate(bdate) === true) {
if (pob.value.match(noScFormat)) {
if (ca.value.match(noScFormat)) {
if (rlg.value.match(letters)) {
if (nsl.value.match(letters)) {
if (cmn.value.match(letters)) {
if (mo.value.match(letters)) {
if (cfn.value.match(letters)) {
if (fo.value.match(letters)) {
if (gn.value.match(letters)) {
if (matchCheck(vrv, rts) === true) {
if (cnValid(cn) === true) {
if (lrn.value.length === 12) {
//Submit Data to db if all of the requirements are passed.
}
else {
//Error Message;
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
The error occurs when the "arrayToBeChecked" value that is passed to the "matchCheck()" function is not an arry. To fix this, you could convert "arrayToBeChecked" to an array if it's not already an array.
function matchCheck(arrayToBeChecked, findingValue) {
// Convert arrayToBeChecked to an array if it's not already an array
if (!Array.isArray(arrayToBeChecked)) {
arrayToBeChecked = [arrayToBeChecked];
}
return arrayToBeChecked.includes(findingValue);
}

specific page redirect to corresponding mobile page not working

I have the following code that works with other circumstances but is giving me problems I guess due to the window.locaton. Please help I need to redirect users to specific mobile pages depending on the desktop page.
function mon() {
if ($('body').is('.mon')) {
return true;
} else {
return false;
}
}
function tue() {
if ($('body').is('.tue')) {
return true;
} else {
return false;
}
}
function wed() {
if ($('body').is('.wed')) {
return true;
} else {
return false;
}
}
function detectmob() {
if (screen.width <= 800) {
return true;
} else {
return false;
}
}
if (detectmob() && mon()) {
window.location = "../m/days/mon.html";
} else if (detectmob() && tue()) {
window.location = "../m/days/tue.html";
} else if (detectmob() && wed()) {
window.location = "../m/days/wed.html";
}
It was my mistake
<body class="mon">
<script src="jquip.min.js"></script><!--increase load time instead of jquery.min-->
<script>
function mon() {
if ($('body').is('.mon')) {
return true;
} else {
return false;
}
}
function tue() {
if ($('body').is('.tue')) {
return true;
} else {
return false;
}
}
function wed() {
if ($('body').is('.wed')) {
return true;
} else {
return false;
}
}
function detectmob() {
if (screen.width <= 800) {
return true;
} else {
return false;
}
}
if (detectmob() && mon()) {
window.location = "../m/days/mon.html";
} else if (detectmob() && tue()) {
window.location = "../m/days/tue.html";
} else if (detectmob() && wed()) {
window.location = "../m/days/wed.html";
}
</script>
working fine

Validation is showing in Start time and end time but it is not showing in Break start and Break end

See the code below
function chk_submit_all()
{
var frm = document.add_advert;
if (frm.avl_after.value.search(/\S/) == '-1')
{
document.getElementById('error_avl_after').innerHTML = 'Please choose date, you are available on or after';
frm.avl_after.focus();
return false;
}
else
{
document.getElementById('error_avl_after').innerHTML = '';
}
var count_all = 0;
$('input:checkbox.choose_days').each(function (index, element )
{
if (this.checked == true)
{
var strt_time = $(this).val();
var strt_val = $('#start_time_'+strt_time).val();
var startTime = new Date().setHours(GetHours(strt_val), GetMinutes(strt_val), 0);
if ($('#start_time_'+strt_time).val() == '')
{
document.getElementById('error_avl_day_time').innerHTML = 'Please choose start time';
breakOut = true;
//alert('Please choose start time');
}
else
{
var end_time = $('#end_time_'+strt_time).val();
var endTime = new Date(startTime)
endTime = endTime.setHours(GetHours(end_time), GetMinutes(end_time), 0);
if (endTime <= startTime)
{
document.getElementById('error_avl_day_time').innerHTML = 'end time should be higher than start time';
// alert('end time should be higher than start time');
breakOut = true;
}
else
{
Else part is not working
please have a look where i have done wrong.
Not entering else part
Validation is showing in Start time and end time but it is not showing in Break start and Break end
//alert ('hii'); die;
// alert($('#radio-'+strt_time+'-brk').val()); die;
if ($('#radio-'+strt_time+'-brk').checked == true)
{
alert ('hii'); exit;
var brk_strt_time_val = $('#break_time_start_'+strt_time).val();
var brk_strt_time = new Date().setHours(GetHours(brk_strt_time_val), GetMinutes(brk_strt_time_val), 0);
if ((brk_strt_time > strt_time) && (brk_strt_time < end_time))
{
//alert (hiii);die;
var brk_end_time_val = $('#break_time_end_'+strt_time).val();
var brk_end_time = new Date().setHours(GetHours(brk_end_time_val), GetMinutes(brk_end_time_val), 0);
if (brk_strt_time >= brk_end_time)
{
//alert('break end time should be higher than break start time'); die;
document.getElementById('error_avl_day_time').innerHTML = 'break end time should be higher than break start time';
//alert('break end time should be higher than break start time');
breakOut = true;
}
else
{
count_all++;
}
}
}
else
{
count_all++;
}
}
}
}
});
if (count_all == 0)
{
document.getElementById('error_avl_day_time').innerHTML = 'Please choose day with time';
return false;
}
else
{
if(breakOut)
{
breakOut = false;
return false;
}
else
{
document.getElementById('error_avl_day_time').innerHTML = '';
}
}
}
This is the answer Coders
function chk_submit_all()
{
var frm = document.add_advert;
if (frm.avl_after.value.search(/\S/) == '-1')
{
document.getElementById('error_avl_after').innerHTML = 'Please choose date, you are available on or after';
frm.avl_after.focus();
return false;
}
else
{
document.getElementById('error_avl_after').innerHTML = '';
}
var flag=0;
var count=0;
var start_time = document.getElementsByName('days_val[]');
var len = start_time.length;
for(i=0;i<len;i++){
if(start_time[i].checked){
var strt_time = start_time[i].value;
var strt_val = $('#start_time_'+strt_time).val();
var end_val = $('#end_time_'+strt_time).val();
if (strt_val=='') {
document.getElementById('error_avl_day_time').innerHTML = 'Please choose a Start time';
flag=1;
break;
}
else
{
if (strt_val>=end_val) {
document.getElementById('error_avl_day_time').innerHTML = 'End Time Must be greater than Start Time';
flag=1;
break;
}
else{
if ($('#radio-'+strt_time+'-brk').is(':checked'))
{
var brk_strt_time_val = $('#break_time_start_'+strt_time).val();
var brk_end_time_val = $('#break_time_end_'+strt_time).val();
if ((brk_strt_time_val=='') || (brk_end_time_val=='')) {
document.getElementById('error_avl_day_time').innerHTML = 'Please Choose Valid Break Time';
flag=1;
break;
}
else
{
if ((brk_strt_time_val=='00:00') || (brk_end_time_val=='00:00')) {
document.getElementById('error_avl_day_time').innerHTML = 'Please Choose Valid Break Start/End Time';
flag=1;
break;
}
else{
if (((brk_strt_time_val <= strt_val) || (brk_strt_time_val >= end_val))|| ((brk_end_time_val <= strt_val) || (brk_end_time_val >= end_val))) {
document.getElementById('error_avl_day_time').innerHTML = 'Break Start/End Must be within Start time and End Time';
flag=1;
break;
}
else
{
if (brk_strt_time_val>=brk_end_time_val) {
document.getElementById('error_avl_day_time').innerHTML = 'Break End time Must be greater than Break Start Time';
flag=1;
break;
}
}
}
}
}
}
}
count++;
}
}
if (count==0 && flag==0) {
document.getElementById('error_avl_day_time').innerHTML = 'Pleas Choose Atleast One Time Slot';
return false;
}
else{
if (flag==1) {
return false;
}
else
{
document.getElementById('error_avl_day_time').innerHTML = '';
}
}
}

Javascript showing alert without refreshing the page

when I click submit button it shows the validation right but after that alert message the page is being refreshed and i loos all other datas from the fields :S, how can i make it to still remain the others field filled.
I tried to remove the window.location.reload() after submit event is called but still not working :S. ANYONE any suggestion?
this is the code:
function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
Two problems...
Missing return
onSubmit="return formValidation();"
Missing return true;
if (validsex(umsex, ufsex)) { return true; }

Categories

Resources