How to use && operator to validate time in ajax requests

I am currently grappling with time validation and feeling a bit perplexed about how to effectively validate both the start_time and end_time using &&. Here is the code I have been working on:

     var re = /^(\d{1,2}):(\d{2})([ap]m)?$/;
    //Start Time
    if($('.start_time').val() != '') {
              if(regs = $('.start_time').val().match(re)) {
                if(regs[3]) {
                  // 12-hour value between 1 and 12
                  if(regs[1] < 1 || regs[1] > 12) {
                    $('.start_time_error').html('<div>Invalid value for hour(s)</div>');
                    $('.start_time').focus();
                    return false;
                  }
                } else {
                    if(regs[1] > 12){
                    $('.start_time_error').html('<div>Invalid value for hour(s)</div>');
                    return false;
                    }
                }
                // minute value between 0 and 59
                if(regs[2] > 59) {
                  $('.start_time_error').html('<div>Invalid value for minute(s)</div>');
                  $('.start_time').val().focus();
                  return false;
                }
              } else {
                $('.start_time_error').html('<div>Invalid time format</div>');
                $('.start_time').focus();
                return false;
              }
              $('.start_time_error').html('<div>Checked</div>');
              return true;
            }else{
                $('.start_time_error').html('<div>Please fill up</div>');
                return false;
            }
            //End time----------
              if($('.end_time').val() != '') {
              if(regs = $('.end_time').val().match(re)) {
                if(regs[3]) {
                  // 12-hour value between 1 and 12
                  if(regs[1] < 1 || regs[1] > 12) {
                    $('.end_time_error').html('<div>Invalid value for hour(s)</div>');
                    $('.end_time').focus();
                    return false;
                  }
                } else {
                    if(regs[1] > 12){
                    $('.end_time_error').html('<div>Invalid value for hour(s)</div>');
                    return false;   
                    }
                }
                // minute value between 0 and 59
                if(regs[2] > 59) {
                  $('.end_time_error').html('<div>Invalid value for minute(s)</div>');
                  $('.end_time').val().focus();
                  return false;
                }
              } else {
                $('.end_time_error').html('<div>Invalid time format</div>');
                $('.end_time').focus();
                return false;
              }
              $('.end_time_error').html('<div>Checked</div>');
              return true;
            }else{
                $('.end_time_error').html('<div>Please fill up</div>');
                return false;
            }

I attempted to use something like:

  if(regs = $('.start_time').val().match(re) && regss == $('.end_time').val().match(re) ) 

However, it did not work as expected and resulted in an error "regss is not defined". Are there any alternative approaches you could suggest? Thank you!

Answer №1

It appears that you might be overcomplicating things. Consider separating your concerns. Your logic contains two main blocks: one for validating the time string and another for manipulating the DOM to display errors. Currently, you are repeating the same logic for two fields. It would be better to abstract this into a function.

It may not be necessary to show multiple errors. If the time is invalid, simply provide a message like "invalid time entered" and guide the user on the correct format using placeholders in the input field or a generic error message.

By following this advice, you can significantly reduce the amount of code while also making it cleaner and easier to understand. For example, here is a sample function using a regex pattern adapted from a Stack Overflow post:

function isTime(str) {
  return /^([1-9]|1[012]):[0-5][0-9]\s*?(am|pm)$/i.test(str);
}

You can now validate your inputs as shown below:

var start = $.trim($('.start_time').val())
  , end = $.trim($('.end_time').val());

if (!isTime(start) || !isTime(end)) {
  $('.generic_error').html('<div>Please enter a valid time (HH:MM AM/PM)</div>');
}

This approach should give you an idea of how to refactor your code to adhere to the DRY principle (Don't Repeat Yourself).

Demo: http://jsbin.com/ayAbUyI/1/edit

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

Is it possible to implement localStorage for auto-filling multiple forms simultaneously on a single webpage

I have been exploring a code snippet by Ke Yang that uses localStorage to synchronize text in form fields across different fields. I am interested in implementing something similar. On a page where I have a library of downloadable items, there are approxi ...

Small collapse Bootstrap navbar on col-sm width

I recently started experimenting with Bootstrap and implemented a collapsable navbar on my website. However, I noticed that on my Galaxy S6 phone, the navbar does not collapse into the button as expected when the screen size is reduced. Is there a way to ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...

What is the best way to display two timers on one page?

I'm having an issue with displaying two timers for a 3-minute countdown. The problem is that the second timer works perfectly, but the first timer doesn't. Even if I remove the second timer, there is still some problem with the first one. The cod ...

Reactivity in Vue not responding when listening from a different object

Can someone help me understand why my Vue object is not reactive to changes in another object? See the code snippet below. exampleObject = { exampleProperty: null } exampleObject.update = function () { this.exampleProperty = 'updated data&apo ...

What is the best way to apply an SVG as the background-image for this text?

After examining the fiddle, it is clear that there is code to set the background of two spans to an image created with svg. The goal now is to achieve this dynamically using javascript (either jquery or raw) on the span with the "help" class, but unfortuna ...

Transforming a THREE.js shader into a PIXI.js shader

I am currently exploring the world of PIXI.js and custom Shaders, and I must admit, it's a bit overwhelming for me. I came across a GLSL Shader (created by DonKarlssonSan) that I would like to convert to PIXI.js in order to compare performance. Any as ...

Having issues with ERR_HTTP_HEADERS_SENT error and receiving a warning related to a promise

I encountered two warnings while working on the code below and I'm unsure how to address these issues. The first warning I received is: Warning: a promise was created in a handler and it seems to be related to a specific line in my code that I have co ...

AngularJS directive for incorporating additional directives lacks functionality

My current project involves creating a directive that will add form groups to a specific div. I'm working on this by linking the directive to a button in my html code. The functionality I am trying to achieve is quite simple, akin to what is shown in ...

Preloader will properly handle websocket connections along with pace js

I recently implemented a preloader on my website built with Ruby on Rails. Everything seems to be working perfectly, except for the fact that due to Pusher websockets, the preloader does not stop and keeps running indefinitely. I attempted to address this ...

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

ReactJS component experiencing issues with loading images

In my React project, there is a directory containing several images, and I am attempting to import them all into a carousel using Bootstrap. The current code looks like this: import Carousel from 'react-bootstrap/Carousel'; const slideImagesFold ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

How about checking the memory usage in Javascript?

Similar Question: Looking for a Javascript memory profiler I am curious about determining the memory consumption of variables in JavaScript. Could it be done at all? ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

What are the ideal strategies for handling asynchronous calls in Vuex?

Currently, I am exploring Vuex and have come across the concepts of using Actions instead of Mutations when dealing with asynchronous code. I find myself pondering whether it is more beneficial to handle all the asynchronous logic within the action itself ...

Creating a promise class in JavaScript

I am in the process of creating a simple promise class with chainable .then() functionality in javascript. Here is my progress so far: class APromise { constructor(Fn) { this.value = null; Fn(resolved => { this.value = resolved; }); ...

Unfortunately, the YouTube iframe Embed feature does not have the ability to adjust audio settings on an

I've been experimenting with the YouTube iframe API and created a simple set of player controls for the YouTube player using Flash CC HTML5 canvas. The controls include a play/pause button, a draggable video bar with buffering visualization, and a vol ...

The chosen selection automatically deactivates the checkbox with a matching value

I am looking for a solution where selecting an option will automatically disable the checkbox with the corresponding value. The existing methods I have come across are static and rely on hardcoded values. <select name="pickOne" id="pickOn ...

Use JavaScript to swap out images

How can I change the image arrow when it is clicked? Currently, I have this code snippet: http://codepen.io/anon/pen/qEMLxq. However, when the image is clicked, it changes but does not hide. <a id="Boton1" class="button" onClick="showHide()" href="j ...