Verify a unique cross-field rule for comparing two time strings, customized by Vee

I am currently facing an issue with validating two time strings in my buefy form using vue. The goal is to ensure that the second time input does not exceed a one-hour difference from the first time input. Both time fields have granularity down to milliseconds.

Here is the script I am using:

import { Validator } from 'vee-validate';

//Cross-field Rules
Validator.extend('isOneHour', (value, [otherValue]) => {
  function toSeconds(time_str) {
    // Extract hours, minutes and seconds
    var parts = time_str.split(':');
    var mili = time_str.split('.')
    // compute  and return total seconds
    return parts[0] * 3600 + // an hour has 3600 seconds
      parts[1] * 60 +   // a minute has 60 seconds
      +parts[2]        // seconds
      + mili[0] / 1000;        //miliseconds

  }
  console.log(value, otherValue); // out
  var difference = Math.abs(toSeconds(value) - toSeconds(otherValue));


  return difference <= 3600;
}, {
    hasTarget: true
  });

Below is the template implementation:

<b-input
            @keyup.native.enter="getData()"
            editable
            :value="startTime"
            @change.native="startTime = $event.target.value"
            placeholder="ex. 11:22:00.000"
            icon="clock"
            v-mask="'##:##:##.###'"
            name="startTime"
            ref="endTime"
          ></b-input>
<b-input
            editable
            name="endTime"
            :value="endTime"
            @change.native="endTime = $event.target.value"
            placeholder="ex. 11:25:30.450"
            icon="stopwatch"
            @keyup.native.enter="getData()"
            v-mask="'##:##:##.###'"
            v-validate="'isOneHour:endTime'"
          ></b-input>

Unfortunately, this code results in an endless loop and eventually crashes the app after encountering the line:

var difference = Math.abs(toSeconds(value) - toSeconds(otherValue));

The error message I receive in the console is:

TypeError: time_str.split is not a function

I am struggling to pinpoint what exactly I am doing wrong here. Any insights or suggestions would be greatly appreciated.

Answer №1

After troubleshooting, I discovered that the issue with my Vee Validate was due to the event being set as empty (""). When I changed it to "blur", the validation started working properly. The actual error stemmed from using error.first('symbol_input') instead of vErrors.first('symbol_input'), based on my errorBagName configuration. Hopefully, this explanation can help others who encounter a similar problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with function arguments and parameters not functioning correctly in a Vuetify project when utilizing the "this" keyword?

In my current Vuetify project, I am trying to achieve a similar functionality as shown in the following plain HTML/JavaScript example: <body> <button id="anid" onclick="idcheck(this.id)"> </button </body> <script> function ...

Prevent form submission using jQuery based on ajax response, or allow it to submit otherwise

After setting up some jQuery code to handle form submission, the functionality is working well when certain conditions are met. However, I am facing a challenge in allowing the form to be submitted if the response received does not match specific criteria. ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

Timeout error occurred in Async.js because the callback was already triggered

Whenever I execute index.js, I encounter an ETIMEDOUT or ECONNRESET error followed by a Callback was already called error. Initially, my assumption was that the issue stemmed from not including a return before calling the onEachLimitItem callback. Consequ ...

sequenced pauses within a sequence of interconnected methods in a class

scenario: There are two javascript classes stored in separate files, each utilizing a different external service and being called within an express.js router. Refer to the "problematic code" section below: route routes.post('/aws', upload.sing ...

My Node/Express service seems to be generating a span in the logs, but I am unable to locate my service in the Ja

Currently, I am in the process of setting up Jaeger tracing for my Node.js microservice using Express.js. After adding a basic GET request handler in my Express app and hitting the endpoint via curl, I notice that a span is created in the logs. However, w ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Discover the latest data in the Laravel and Vue.js integration

My edit page is located at: http://localhost/smp/post/12 https://i.stack.imgur.com/5KAbo.png API ROUTE: Route::get('package', [ProductController::class, 'update']); In ProductController.php public function update(Request $request) { ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

When all y values are zero, Highcharts.js will shift the line to the bottom of the chart

Is there a way to move the 0 line on the y axis to the bottom of the chart when all values are 0? I attempted the solution provided in this post without success. Highcharts: Ensure y-Axis 0 value is at chart bottom http://jsfiddle.net/tZayD/58/ $(functi ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

How to make a specific table row stand out using AngularJS and CSS

Can you provide advice on how to highlight a specific row in a table? I have a table along with some angular code snippets. Here's an example: angular.module('myApp', []).controller('myTest', function($scope) { var data = []; ...

What could be causing the second image to not drop in the proper position in an HTML and JavaScript environment?

I am encountering an issue with a simple drag and drop implementation using images in my code. The first image works fine, but for some reason the second image does not display correctly when dragged inside the div boxes; it appears outside of the box. Can ...

Utilize Jquery to dynamically update form input in real time based on checkbox selections

I am working on a form that requires real-time calculation of GST (Goods and Services Tax) directly within the form (GST = Price/11) This functionality has been implemented with the following script. Additionally, the calculation needs to be adjust ...

How can you handle setting an array in JavaScript if a key/value pair does not exist when attempting to get it from a JSON object?

When dealing with a large JSON table stored in localStorage and a user-provided key, I need to access the associated value. However, if the key and/or value does not exist, my intention is to create them. But there's a roadblock... The JSON data prov ...

Encountering issues with bidirectional data binding functionality

I have integrated a pagination component from ng-bootstrap into a generic component that includes a select dropdown to choose the number of items per page. I triggered an event from this generic component and caught it in the parent component (member-list. ...

Troubleshooting incorrect elements collapsing or opening in Bootstrap

This Vue project includes a component with the following code: <template> <div class="card card-body text-center m-3" style="max-width: 500px;"> <h3 class="d-inline m-3">{{this.task.title}}</h3> ...

What is the best way to create a dynamic graph in amcharts during runtime?

Below is the code for Multiple Value Axes: In this code, we aim to display a graph using dynamically generated random data. When executed, nothing will happen. <script> var chart; var chartData = []; // generate some random data within a different ...

storing data in local storage using JavaScript

As someone new to coding, my aim is to create a basic "daily planner" page where users can input text on different lines. I've been attempting to use local storage for this task, but seem to be running into some issues. I've experimented with get ...

What is the best way to dissect emails using Haraka?

After delving into the haraka project (at ), I managed to successfully install it on my linux machine. Now, I'm interested in finding a comprehensive tutorial on parsing email meta headers and content body using haraka. Despite searching through their ...