Why isn’t my Zod validation error displaying in React Hook Form when validating an array of strings?

I’m using React Hook Form with Zod validation to implement an OTP (One-Time Password) form where users input a 6-digit OTP, with each digit in a separate input field. I’m using z.object to validate that the OTP consists of exactly 6 numeric digits, and I expect validation errors to display when incorrect input is provided or when less than 6 input is submitted .

Here’s my otpSchema and the relevant code:

const otpSchema = z.object({
  otp: z
    .array(
      z.string().regex(/^d$/, 'Each input must be a single digit'), // Ensure it is a number
    )
    .length(6, 'OTP must consist of exactly 6 digits')
    .nonempty({
      message: "Can't be empty!",
    }),
});

const {
  register: verifyOtpRegister, //unused
  handleSubmit: verifyOtpSubmit,
  trigger: verifyOtpTrigger,
  control,
  getValues: getVerifyOtpValues,
  formState: { errors: verifyOtpErrors },
} = useForm({
  resolver: zodResolver(otpSchema),
});

const onVerifyOtp = (data?: any) => {
  console.log({ error: verifyOtpErrors.otp });
  console.log({ data });
  verifyOtp();
};

I’m rendering 6 separate input fields for the OTP, like this:

{[...Array(6)].map((_, index) => (
  <Grid item key={index}>
    <Controller
      name={`otp[${index}]`}
      control={control}
      render={({ field }) => (
        <TextField
          {...field}
          id={`otp-input-${index}`}
          inputMode="numeric"
          inputProps={{
            maxLength: 1,
            pattern: '[0-9]*',
          }}
          onChange={(e) => {
            console.log(e);
            handleInputChange(e, index, field);
          }}
          onKeyDown={(e) => handleKeyDown(e, index)}
          value={field.value || ''}
          autoComplete="off"
          sx={{ width: 40, textAlign: 'center' }}
        />
      )}
    />
  </Grid>
))}

<FormHelperText error>
  {`${verifyOtpErrors?.otp?.message || ''}`}
</FormHelperText>

<button
  type="submit"
  className="bg-blue-500 text-white py-2 px-4 rounded mt-4"
  onClick={() => {
    console.log(verifyOtpErrors?.otp);
    verifyOtpSubmit(onVerifyOtp);
  }}
>
  Verify OTP
</button>

The issue:

  • When I input the correct valid OTP format (e.g., 123456), the flow works, and the form successfully validates and submits.
  • However, when I enter invalid data (e.g., adb123, empty fields, or less/more than 6 digits), the flow doesn’t work as expected but validation doesn’t display any error messages. The errors.otp object is logged as undefined, and no error is shown in the FormHelperText.

What I’ve tried:

  • Added a console.log(verifyOtpErrors?.otp) in the onVerifyOtp function to debug, but verifyOtpErrors?.otp is always undefined for invalid input.
    Used verifyOtpTrigger('otp') to manually trigger validation, but it still doesn’t populate the error messages and is undefined.
    Ensured that the name in Controller matches the schema (otp[index]).

“Unable to preventDefault inside passive event listener invocation” for touchstart event listener

Google PageSpeed Insights is flagging a website of mine with “Use passive listeners to improve scroll performance”. I’ve successfully resolved this issue for scroll event listeners, but I’ve run into an issue with a “touchstart” listener that I can’t get around.

I have the following code, for users on touch devices, that when tapping a top-level main navigation menu link that has a dropdown, on the first tap it will expand the dropdown (via toggled CSS class), and not follow the top level link. If you tap the top level link a second time, when the dropdown is already expanded, it will follow the link.

document.querySelectorAll( "#primary-nav>ul>li.menu-item-has-children>a" ).forEach( elem => {
  elem.addEventListener( 'touchstart', (e) => {
    let parent = elem.parentElement;
    parent.classList.toggle( 'expand' );
    if( parent.classList.contains( 'expand' ) ) {
      e.preventDefault();
    }
  }, { passive: true } );
});

Adding { passive: true } towards the end broke the code. I get a console error which says “Unable to preventDefault inside passive event listener invocation”, and it follows the link on the first tap. If I remove the “e.preventDefault()” as suggested here, then it also follows the link on first tap.

Can anyone suggest a way around this? Your help would be greatly appreciated.

How can I blur an image in a specific spot?

I am trying to make an effect where, when I hover over an image, that part of the image where my cursor is becomes blurred.

I’ve tried multiple methods to approach this problem, such as using SVGs (Code for what I’m currently trying is provided below), as well as just a normal div with a blur backdrop-filter. However, they all lead to the same problem in which the border of the blurring element is sharp, so it ends up looking like the image provided. Instead, I want the blur effect to look like it slowly merges into the image. How can I achieve that effect? Also, I am a beginner at web development, so I would appreciate answers which explain everything in baby steps. Thanks a lotThe output of previously tried solutions

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blurred Circle Effect</title>
  <link rel="stylesheet" href="styles.css">
  <style>
    .container {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url('https://via.placeholder.com/400');
  background-size: cover;
}

.container::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: inherit;
  background-size: inherit;
  filter: blur(10px);
  clip-path: circle(20% at center); /* Adjust the circle size */
  pointer-events: none; /* Prevent interaction with the pseudo-element */
}

  </style>
</head>
<body>

  <div class="container"></div>

</body>
</html>

jQuery in functions.php – Uncaught TypeError: $ is not a function

I’m trying to add a small amount of code to a WordPress site in the functions.php file. I’ve tested the code in Codepen and it works perfectly.

However, when I add it to the site, I get the following error message in the console

Uncaught TypeError: $ is not a function

I feel like I’m close, but obviously not close enough! I’d be grateful for any advice.

add_action('wp_footer', 'wpb_hook_javascript_footer');
function wpb_hook_javascript_footer() {
    ?>
    <script>
var thehours = new Date().getHours();
var theday = new Date().getDay();
    var themessage;
    var morning = ('Order before 2pm for guaranteed dispatch TODAY');
    var evening = ('Order now for guaranteed dispatch TOMORROW');
    var friday = ('Order now for guaranteed dispatch on MONDAY');

    if ((thehours >= 0 && thehours < 14 && theday == 1) ||
    (thehours >= 0 && thehours < 14 && theday == 2) ||
    (thehours >= 0 && thehours < 14 && theday == 3) ||
    (thehours >= 0 && thehours < 14 && theday == 4)) {
     themessage = morning;

    } else if ((thehours >= 14 && thehours < 24 && theday == 1) ||
               (thehours >= 14 && thehours < 24 && theday == 2) ||
               (thehours >= 14 && thehours < 24 && theday == 3) ||
               (thehours >= 14 && thehours < 24 && theday == 4) ||
               (thehours >= 0 && thehours < 24 && theday == 0)) {
                themessage = evening;

    } else if ((thehours >= 14 && thehours < 24 && theday == 5) ||
               (thehours >= 0 && thehours < 24 && theday == 6)){
                themessage = friday;
  }

    $('.checkout_dispatchtime').append(themessage);
    </script>
    <?php
}

Playwright Test Running Twice Even with Worker Set to 1

I’m facing an issue where my Playwright test runs twice, even though I’ve configured the workers option to 1 in my Playwright config. Below is a snippet of my configuration:

timeout: 20 * 60 * 1000,
/* Run tests in files in parallel */
fullyParallel: false,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 1 : 0,
/* Opt out of parallel tests on CI. */
workers: 1,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */

Here’s an example of my test structure:

test.describe("First Step", () => {
  test.beforeAll(async () => {
    // Setup code
  });

  test("Single test", async () => {
    // Test code
  });

  test.afterAll(async () => {
    // Teardown code
  });
});

However, when I run this single test, it shows the following in the console:
Running 2 tests using 1 worker

Even though I only have one test defined, Playwright identifies it as two tests.

What I’ve Tried
Ensured the workers option is set to 1 in the configuration.
Verified the test structure to confirm there’s only one test present.
Consulted ChatGPT, but the suggestions didn’t resolve the issue.
Goal
I need my test to execute only once, regardless of the worker count or configuration.

Has anyone encountered a similar issue? If so, how did you resolve it?

Saving scroll momentum for touch interface devices when using scrollTo

I am currently writing a website where, when you reach a certain position, you are thrown up to an identical position without any animation. Because of this, it should feel like you’re endlessly scrolling. I used the window.scrollTo function to implement this. At the same time, it works perfectly on a computer and laptop. However, when used on a phone, the scroll speed is reset when moving up. How can this be fixed?

You need to at least understand the cause of the problem, and at best immediately find out its direct solution.

This is example of code

HTML

<section class="galery">
    <section class="column1">
        <section class="item" id="101">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="102">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="103">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="104">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="105">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="106">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="107">
            <img class="galery_item" alt="Picture">
        </section>
    </section>
    ***Other column***
</section>

JS

if('ontouchstart' in window || navigator.maxTouchPoints){
    window.addEventListener('touchend', () =>{
        flag = true;
    });
    window.addEventListener('touchstart', () =>{
        flag = false;
    });
    window.addEventListener('scroll', () =>{
        if(flag){
            if(***coordinates of the lower boundary*** <= pageYOffset){
                window.scrollTo(0, ***coordinates of the indented upper boundary***);
            }
            else if(***coordinates of the upper boundary*** >= pageYOffset){
                window.scrollTo(0,  ***coordinates of the indented lower boundary***);
            }
        }
    });
}

this is what the site looks like

enter image description here

when the user reaches a certain lower limit, he is thrown up to the same picture. The result is a visual effect of endless scrolling. But on devices with touch interface, the scrolling pulse is not saved when the scrollTo function is triggered and the screen stops abruptly. This needs to be fixed.

There have been attempts to make the main event trigger a function like touchend rather than scroll, but this has led to the user reaching the bottom of the site too quickly and having to greatly increase the html code.

How to achieve a very smooth native like scrolling on mobile browser?

I have exhausted all my CSS and javascript knowledge and I still could not figure out how they optimize their mobile website so much that it scrolls like a native app, even with images and videos that are occupying most of the viewport, it still scrolls very smooth.

I have tried

scroll-behavior: smooth;

in my CSS containers

and javascript

document.querySelector(target).scrollIntoView({ behavior: 'smooth' });

and I have even tried

will-change: transform;

attribute on a parent container that transforms content upwards computed by javascript. That is probably the worst performing one in my test.

How does facebook do it?

FabricJS v6 set Background Image

The documentation of Fabric JS says they dropped support for setBackgroundObject and setBackgroundImage both of which could be set to update the canvas to have a background image:

e.g

canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
    backgroundImageOpacity: 0.5,
    backgroundImageStretch: false
});

//or the more convoluted:
const rect = new Rect({
  left: 0,
  top: 0,
  width: canvas.width || 0,
  height: canvas.height || 0,
  fill: "transparent",
  opacity: 0,
  stroke: "transparent",
  strokeWidth: 0,
  selectable: false,
  hasControls: false,
});
const img = new FabricImage(url, {
  crossOrigin: "anonymous",
});
img.scaleToHeight(canvas.width || 0);
img.scaleToWidth(canvas.height || 0);
rect.set("backgroundImage", img);
canvas.setBackgroundObject(rect);

How to do it in V6?

The documentation is not clear in how they expect this to be done:

rm setBackgroundColor, setBackgroundImage, setOverlayColor, setOverlayImage: assign the property directly and render the canvas

Attempts:

// Attempt A: (doesn't update the background)
const img =  FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
canvas.set("backgroundImage", img);
canvas.renderAll();

//Attempt B: 
// This leads to the error below:
canvas.backgroundImage = FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
canvas.renderAll();

Type ‘Promise<FabricImage<Partial, SerializedImageProps, ObjectEvents>>’ is missing the following properties from type ‘FabricObject<Partial, SerializedObjectProps, ObjectEvents>’: noScaleCache, lockMovementX, lockMovementY, lockRotation, and 223 more.ts(2740)
(property) StaticCanvas.backgroundImage?: FabricObject<Partial, SerializedObjectProps, ObjectEvents>
Background image of canvas instance. since 2.4.0 image caching is active, please when putting an image as background, add to the canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom vale. As an alternative you can disable image objectCaching

The scaleX() function in the Konva.js library shifts the coordinates of the Konva.Text() object

I need to recreate an inverted version of an original 2d model side by side.

I can achieve this with scaleX(-1) but the text is upside down.

When I scaleX(-1) again on the inverted model, the coordinates of the text are distorted, how can I solve this problem?

the one on the left is the original model and the one on the right is the reversed model. I made the backgrounds yellow to make it clearer that it has shifted.

to give an example from part of the code

function mmToPx(mm) {
    return mm * dimensions.currentScale;
}
 // Bobin
    const coil = new Konva.Rect({
        x : centerX - (mmToPx(dimensions.R1 - dimensions.r2) - mmToPx(1)) / 2,
        y : centerY - (mmToPx(dimensions.Ls) - mmToPx(1)) / 2,
        width : mmToPx(dimensions.R1 - dimensions.r2) - mmToPx(1),
        height : mmToPx(dimensions.Ls - dimensions.ts) - mmToPx(1),
        fill: '#ff7f27',
        stroke: 'black',
        strokeWidth: 5,
    });
    
 const lines = [
...,
{
            isText : true, 
            width : coil.width(),
            text: 'N,I',
            textX: coil.x(),
            textY: (coil.y() + (coil.height() / 2)) - (dimensions.currentScale / 2),
            textColor : 'black',
        },
...,
];

lines.forEach(line => {
...,
if(line.isText){
            var text = new Konva.Text({
                x: line.textX,
                y: line.textY,
                text: line.text,
                fill: line.textColor,
                fontFamily: 'Calibri',
                fontSize: 14,
                align : 'center',
                width : line.width,
            });
            
            
            const textBackground = new Konva.Rect({
                x: line.textX,
                y: line.textY,
                width: line.width,
                height: 20, 
                fill: 'yellow',
                cornerRadius: 4, 
            });
            originalGroup.add(textBackground);
            originalGroup.add(text);
        }
});

and here is the scaleX() method

   const mirrored = originalGroup.clone();
    mirrored.x(centerX * 2.35)
    mirrored.scaleX(-1);
    mirrored.find('Text').forEach((textNode) => {
        textNode.scaleX(-1);
    });
[![enter image description here][1]][1]

How to Identify a image is portrait or landscape image in react js?

how to dynamically identify whether an image is in portrait or landscape orientation using React.js. This guide explains the steps to analyze image dimensions and apply conditional styling to ensure your application adapts seamlessly to varying image formats.

I attempted to calculate the image’s width and height using React.js and conditionally applied styles based on the orientation (portrait or landscape). I expected the component to accurately detect the image orientation and dynamically adjust the styling to fit the layout requirements.

How can I “include” js-code from several js-files into main html-file?

I had a lot of javascript(js)-code in my previous html-file.
I have moved part of the code in another js-files – file1, file2 – see code below.
Before moving I didn’t take care about order of functions declarations. It was OK.
After moving the order began to matter.

I have used defer attribute to force the browser to download all the scripts before they start executing.
But when the main code starts to execute the browser reported an error – function in file1/2 are not defined.

The question is: how can I move a part of js-code into another js-file and not worry about the order of inclusion of additional files and the order of functions declarations in the main code?

html...
 
<script>
     the main js-code - previously all js-code, including file1 and file2, was placed here
</script>
 
<script defer src="file1.js"></script>
<script defer src="file2.js"></script>

The login system works on localhost but fails on the online server [closed]

I developed a website with the possibility to register and log in, using the following structure:

|-- includes
|-- public_www
|---|-- src
|---|-- private
  • includes: Contains sensitive files (configuration, etc.).
  • public_www: Contains my web pages (index.php, signin.php, signup.php, etc.).
  • src: Contains resources for my pages.
  • private: Contains processing files (process_signin.php, process_signup.php, etc.).

In the private folder, there is a .htaccess file to enhance security by blocking direct access to the .php files, except from the server itself.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

<FilesMatch ".php$">
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</FilesMatch>

-> Problem encountered:
The form in signin.php (form) uses process_signin.php (logic), which is located in the private folder. After submitting the form, I return to the signin.php page without any processing being done. Here is an excerpt of the code:

<?php

include __DIR__ . '/../../includes/db_connection.php';
include_once __DIR__ . '/../../includes/logger.php';

session_start();

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    // More code .....
   
} else { // I encountered this situation
    $_SESSION['error_message'] = "";
    header("Location: /sign-in.php");
    exit();
}
?>

The following elements are well-defined: folder security and accessibility, page and directory names.

I have already tested these files on my local environment (localhost), and everything works perfectly. However, when I upload the site online, this problem occurs. I even tried moving process_signin.php to public_www (while respecting the directory changes), but the problem persists. Has anyone encountered the same issue, or do you have any suggestions for resolving this?

TypeError: This WritableStream is currently locked to a writer

I’m experimenting with cloudflare’s workers to connect to an SMTP server (port 2525 instead of 25). While trying to use multiple writers by closing one before starting another, I always got the error: TypeError: This WritableStream is currently locked to a writer.. What am I doing wrong? This is my code:

export default {
  async fetch(req){
    const addr = { hostname: "mail.domain.example", port: 2525 };

    try {
      const socket = connect(addr, { secureTransport: "starttls", allowHalfOpen: false });
      const encoder = new TextEncoder();

      let encoded = encoder.encode("EHLO examplern");

      const writer1 = socket.writable.getWriter();
      await writer1.write(encoded);
      await writer1.close();

      const writer2 = socket.writable.getWriter();
      await writer2.write(encoded);
      await writer2.close();

    } catch (error) {
      console.log(error);
    }
  }
}

When running this code, it logs the error message. When I run tcpdump on my server, I can see the first EHLO, but not the second one.

Arrow Function in React JS

I was creating a form using React, and displaying an array of users’ names and Ids. while adding a delete button to allow deleting a user from the list.

my question is when I added the handleDelete function

const handleDelete = (id) => { const newUsers = users.filter((person) => person.id !== id); setUsers(newUsers); };
when I add this function the the button as onClick={handleDelete(user.id)}

it doesn’t work but when I add it as onClick={() => handleDelete(user.id)}
it work, can anyone explain the difference between these two ways?