validating date format in the formats of us and euro [duplicate]

I am defiately a noob in regex, i had the code which is working good but the problem is that validation of date is not perfect, it checks for 2 disits of date and 2 digits of month and 2 digits of year but i want to have a proper validation of date using a regex, even my code works but it is missing the validation of date,

Many will suggest to use date field, but as per requirement, i cannot do so.

Here is the fiddle i have

https://jsfiddle.net/05oe4hzn/

Fiddle code is here

<form action="">
  <input class="startDate date" data-message="Invalid start date" 
  placeholder="DD/MM/YYYY" />
  <input class="endDate date" data-message="Invalid end date"
  placeholder="DD/MM/YYYY" />
  <input type="submit">
</form>
<hr/>
<form action="">
  <input class="startDate date" data-message="Invalid start date" 
  placeholder="MM/DD/YYYY" />
  <input class="endDate date" data-message="Invalid end date"
  placeholder="MM/DD/YYYY" />  
  <input type="submit">
</form>

and a JS Code

const dateRegex = {
  "MM/DD/YYYY": /(?<month>d{2})/(?<day>d{2})/(?<year>d{4})/,
  "DD/MM/YYYY": /(?<day>d{2})/(?<month>d{2})/(?<year>d{4})/
};
const getDate = (dateString, format) => {
  const result = dateRegex[format].exec(dateString);
  if (!result) return -1;
  const { year,month,day } = result.groups; // spread
  const date = new Date(year, month-1, day, 15, 0, 0, 0);
  console.log(dateString,year,month,day,"n",date)
  return isNaN(date) ? -1 : [date, +year, +month, +day]; // return date and parts
};

const validateDate = formElement => {
  const value = formElement.value.trim();
  if (value === "") return true; // only test actual values
  const dateValid = getDate(value, formElement.placeholder)
  if (dateValid === -1) return false; // not matching format
  const [date, year, month, day] = dateValid;
  console.log(date.getFullYear(),"===",year,date.getMonth(),"===",(month - 1),date.getDate(),"===",day); // remove this after testing
  return date.getFullYear() === year && 
         date.getMonth() === (month - 1) && 
         date.getDate() === day;
};
$("form").on("submit", function(e) { // passing the submit event
  $(".date",this).each(function() { // only the dates in this form
    if (!validateDate(this)) {
      alert($(this).data("message"));
      $(this).focus();
      e.preventDefault(); 
      return false; // stop processing dates
    }  
  })
})

Looking to compare json files for differences using the word part of the json file

I am parsing the JSON file into a javascript object just having trouble accessing the word in each object unsure how to go about doing it.
JSON file looks like this:

 "words": [
        {
            "word": "all",
            "start": 260.80997,
            "end": 260.90497,
            "confidence": 0.38183594,
            "punctuated_word": "All"
        },
        {
            "word": "right",
            "start": 260.90497,
            "end": 261,
            "confidence": 0.81152344,
            "punctuated_word": "right."
        },

I have tried using the dot operator and doing obj[key] but get undefined

How do I make this check writing function support any number over 1000?

Here is the function:

function generateCheckText(amount) {
  // Convert the dollar amount to a string and split it into parts
  // by the decimal point
  const parts = amount.toString().split('.');

  // Convert the dollar amount to a written out number in English
  let writtenAmount = convertToWrittenNumber(parts[0]);

  // If there are cents, add them to the written amount
  if (parts.length > 1) {
    writtenAmount += ` and ${convertToWrittenNumber(parts[1])} cents`;
  }

  // Return the generated check text
  return `Pay to the order of [Payee] the sum of ${writtenAmount} dollars.`;
}

// Helper function to convert a number to its written out form in English
function convertToWrittenNumber(number) {
  // Array of English words for the different units of numbers
  const units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

  // Array of English words for the different tens places of numbers
  const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

  // Array of English words for the different teens of numbers
  const teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];

  // If the number is zero, return the word for zero
  if (number === 0) {
    return 'zero';
  }

  // If the number is less than ten, return the word for the units place
  if (number < 10) {
    return units[number];
  }

  // If the number is less than 20, return the word for the teen
  if (number < 20) {
    return teens[number - 10];
  }

  // If the number is less than 100, return the word for the tens place and the units place
  if (number < 100) {
    return `${tens[Math.floor(number / 10)]} ${units[number % 10]}`;
  }

  // If the number is greater than or equal to 100, return the word for the units place,
  // the word for the tens place, and the word for the hundreds place
  return `${units[Math.floor(number / 100)]} hundred ${convertToWrittenNumber(number % 100)}`;
}

console.log(generateCheckText(1174.30));

It only works for numbers under 1000. I need it to support any dollar amount.

dataTables – Uncaught TypeError: Cannot read properties of undefined reading

I work with dataTables and responds data like this:

 {
        "draw": "1",
        "iTotalRecords": 1,
        "iTotalDisplayRecords": 1,
        "aaData": [
            {
                "id": "6",
                "subject": "Hello",
                "body": "please check your system immediately",
                "sender_id": "2",
                "reciever_id": "1",
                "status": "{"1": {"is_flag": 1, "is_label": 1, "is_delete": 1, "is_archive": 1, "is_favorite": 1}, "2": {"is_flag": 1, "is_label": 1, "is_delete": 1, "is_archive": 1, "is_favorite": 1}}",
            }       
        ]
    }

As you see, status has JSON format data in MySQL database like that:

{
    "1": { // num 1
        "is_flag": 1,
        "is_label": 3,
        "is_delete": 1,
        "is_archive": 1,
        "is_favorite": 0
    },
    "2": { // num 2
        "is_flag": 1,
        "is_label": 1,
        "is_delete": 1,
        "is_archive": 1,
        "is_favorite": 1
    }
}

So, I need to render status data with dataTables rowCallback method with if conditional to select num and then addClass into row like this:

    rowCallback: function(data, type, row) {
        var num = 1;
        if(row.status.num.is_archive  == 1){
            $(row).addClass('selectRow');
        }
    }

In action I see this error:

Uncaught TypeError: Cannot read properties of undefined (reading ‘num’)

How do can I fix this error?!

navigation from landing page data does not displaying even the correct API redux [closed]

data does not displays even in console panel something outlet problem.

const ProdcutDetail = () => {
  const product = useSelector((state) => state.product);
  const dispatch = useDispatch();
  const { productId } = useParams();

  console.log(product);

  const { image, title, price, category, description } = product;
  const fetchProductDetail = async () => {
    const response = await axios
      .get(`https://fakestoreapi.com/products/${productId}`)
      .catch((err) => {
        console.log("Err: ", err);
      });
    dispatch(selectedProduct(response.data));
  };

  useEffect(() => {
    if (productId && productId !== "") fetchProductDetail(productId);
    return () => {
      dispatch(removeSelectedProduct());
    };
  }, [productId]);
const intialState = {
  products: [],
};

export const productsReducer = (state = intialState, { type, payload }) => {
  switch (type) {
    case ActionTypes.SET_PRODUCTS:
      return { ...state, products: payload };
    default:
      return state;
  }
};

export const selectedProductsReducer = (state = {}, { type, payload }) => {
  switch (type) {
    case ActionTypes.SELECTED_PRODUCT:
      return { ...state, ...payload };
    case ActionTypes.REMOVE_SELECTED_PRODUCT:
      return {};
    default:
      return state;
  }
};

Home component all the data are displaying but on click it render the next page id on localhost wrong in to display data.

how to fix it and why its happening ?

It should be display next page on click the cards.

how to randomize this quiz javascript [closed]

This resource I got from Google, I have tried how to make the quiz random but I didn’t find a good way to randomize the quiz.

Is there an easy way to randomize the quiz? I tried using shuffle but it failed, maybe because I’m still a beginner so I still lack knowledge.

html css

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Picture Quiz</title>
<style>
body {
background-color: #eeeeee;
}
.grid {
width: 68%;
height: 520px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}

.buttons img
{
width:200px;
}
.grid h1 {
font-family: "sans-serif";
background-color: #ffc107;
font-size: 35px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
hr
{
margin-top: 50px;
    color: red;
    background-color: #ffc107;
    height: 2px;
    border: none;
}
#score {
color: #ffc107;
text-align: center;
font-size: 30px;
}

.grid #question {
font-family: "monospace";
font-size: 30px;
color: #ffc107;
}

.buttons {
margin-top: 30px;
}

#btn0,
#btn1,
#btn2,
#btn3 {

    padding: 0px;
font-size: 20px;
color: #fff;
    border: none;
margin: 10px 20px 10px 0px;

}

#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #ffc107;
}

#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}

#progress {
color: #2b2b2b;
font-size: 18px;
}
</style>
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Picture Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
<script src="index.js" type="text/javascript"></script>
</html>

js

var images = {
"dog"  : "dog.jpg",
"cow" : "cow.jpg",
"cat" : "cat.jpg",
"goat"   : "goat.jpg",
"deer"   : "deer.jpg",
"hen"   : "hen.jpg",
"lion"   : "lion.jpg",
"parrot"   : "parrot.jpg",
"tiger"   : "tiger.jpg"

}  
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;

// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}

showProgress();
}
};

function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};

function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};

// create questions
var questions = [
new Question("Which one is dog?", ["cow", "goat", "cat", "dog"], "dog"),
new Question("select tiger below", ["parrot", "deer", "tiger", "lion"], "tiger"),
new Question("choose parrot pls?", ["hen", "parrot", "goat",  "dog"], "parrot"),
new Question("Find cat below?", ["parrot", "goat", "cat", "tiger"], "cat"),
new Question("choose lion pls?", ["lion", "goat", "tiger", "dog"], "lion")
];

function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}


function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}

this.questionIndex++;
}

Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();

I tried if it was refreshed or answered on it would bring up a random quiz
enter image description here

Thank you

React hooks, Error handling. How should I do when using MVP(Model-view-presenter)?

I’m doing a login view for my application and I have at tough time getting this right. I’m pretty new at this so the solution may be trival for you. I have a presenter and a login view, now I want to catch the error in the presenter and then send it over as prop to my view and handle it there. How should I go about solving this?

My first solution was to just solve everything in the presenter but that seemed wrong to do that because it doesn’t follow the rules of MVP.

[Login view(https://i.stack.imgur.com/uSdJA.png)
Login presenter

Dynamic Html elements click event Manage

I am using plan Javascript to manage my code, I have certain elements which are appended after certain actions has been performed. I want to trigger click event on those elements, predefining click event by classname is not working as JS gets loaded and DOM elements are updated later on.

SO to avoid that I have used this to solve the problem

document.body.addEventListener('click', event => {
      if (event.target.className == 'close-image') {
          //certain operations
      }
}

But this isn’t ideal solution, because everytime input buttons are pressed it goes out checking className, so any alternative to use this?

I am not using jquery else I would have managed it

How do I implement the backend part for mail on JS, give me a hint

I have a creative task to create an analog of mail. I understand the frontend, but I have no idea about the backend at all =(. Don’t hit me =). I need to figure out how to make a server for this application. We are given a json database file with the project source data. “All application statics should be distributed by the server.”
To implement the API, it is forbidden to use any libraries on the backend, except for the standard ones for Node.js version 18.12.1 (LTS).
I would like to hear from those people who understand this, which way I should move to do this. Then I’ll figure it out myself. Thanks!!!
layout 1
layout 2

How to display on the page the data that was displayed in the console

In a small application made with Express.js, I print text to the console every second and after 4 seconds I stop the text output to the console. I need to return the current date to the page after the input to the console has expired. How can I do this?

var express = require("express");
var app = express();

app.get("/", (req, res) => {
  const utcStr = new Date().toUTCString();
  function outputText() {
    console.log(utcStr);
  }
  const interval = setInterval(outputDate, 100);
  setTimeout(() => {
    clearInterval(interval);
  }, 4000);
  res.send();
});

app.listen(3000);

I would like to know if there is a way to check in Javascript if a bitmap image is a valid mask image?

I want to place a main bitmap on canvas (jpg,png) and I also want to upload a bitmap file that is going to perform as a mask of the main bitmap.

I would like to know if there is a way to check in Javascript if a bitmap image is a valid mask image? (Like the uploaded image)

I have created a codepen and upload a mask image. If you upload a mask image, you can see the changes on main bitmap on canvas, and if you upload a non mask image nothing will change. I need to validade the mask image by code in some way

`context.drawImage(bg, 0, 0, canvas.width, canvas.height);
maskInput.addEventListener('change', () => {
    mask.src = URL.createObjectURL(maskInput.files[0]);
    mask.onload = function() {  
        maskImage.setAttribute('src', mask.src)
        isMaskValid(maskImage)
     draw()
    }
})

function isMaskValid(maskImage){
//   todo
}
//You can check all code here
https://codepen.io/thaisdsilve/pen/zYaENbx`

enter image description here

Modify grid to use full height but not more

The following snippet works (you have to run it in “Full page”, see button on the right after running a snippet), but it exceeds the browser height when an element is clicked. Why is grid-auto-rows: fit-content(50%) fit-content(50%); not enough to prevent this to happen?

How to fix this, in order to have all elements visible in a single page, without having to scroll? (Click on an image to see the problematic layout)

var $ = document.querySelector.bind(document);
var $$ = document.querySelectorAll.bind(document);
$('body').addEventListener('click', (event) => {
    $$('.container > div').forEach(element => element.classList.remove('clicked'));
    $('.container').classList.remove('clicked');
    if (event.target.tagName == "IMG") {
        event.target.closest('.container').classList.add('clicked');    
        event.target.closest('.box').classList.add('clicked');
    }
});
.page { max-width: 80%; max-height: 80%; margin: auto; border: 1px solid black; } 
.container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-auto-rows: fit-content(50%) fit-content(50%); gap: 0.5rem; }
.container img { max-width: 100%; }
.box { background-color: gray; }
.container.clicked { grid-template-columns: 1fr 1fr 4fr; grid-auto-rows: 1fr 1fr 1fr; }    
.box.clicked { grid-column: 3 / 4; grid-row: 1 / 4; padding: 10px; background-color: yellow; }
.container.clicked .box:not(.clicked) { grid-auto-flow: column; }
<div class="page">
    <div class="container">
        <div class="box">Hello world <img src='https://picsum.photos/id/237/200'></div>
        <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
        <div class="box"><img src='https://picsum.photos/id/241/300'></div>
        <div class="box"><img src='https://picsum.photos/id/242/400'></div>
        <div class="box"><img src='https://picsum.photos/id/238/500'></div>
        <div class="box"><img src='https://picsum.photos/id/239/200'></div>
    </div>
</div>

How to redirect to an image while click on test or id in word addin using office js?

please view the attached image for output

this is the code I have written in js

Office.context.document.addHandlerAsync(
        Office.EventType.DocumentSelectionChanged,
        (result: any) => {
          let bookmark = localStorage.getItem("bookmark")
          let bookmarkParse = JSON.parse(bookmark);
          console.log("bookmarkParse",bookmarkParse)
          bookmarkParse.map((item: any) => {
          Word.run(async (context) => {
            console.log("result", result);
            const range = context.document.getSelection();
            console.log("getRange",range)
            return context.sync().then(async function ()
            {
              context.load(range);
              await context.sync();
              let text = range.text
              console.log("item", item.ImageId, text);
              
  
              if (item.ImageId == text) {
                console.log("item bookmark",item.bookmark)
                range.hyperlink = "#" + item.bookmark;
                console.log("range.hyperlink",range.hyperlink)
                console.log(item.bookmark,"range matched");
              } else {
                console.log("range not matched");
              }
              await context.sync();
            });

here is the my code for redirected to image when clicking on the test.