Differences between using ng-pattern and scripting for validation

My goal is to validate a date in the format YYYY/MM/DD using a regular expression ng-pattern. When I use the code below in the UI, it works perfectly fine.

<input type="text" class="k-fill" ng-pattern="/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/" ng-model="Request.ExpDate" id="ExceptedDate" name="ExceptedDate" ng-readonly="true" required />

However, I would like to validate this pattern within a function so that I can display a validation message in a pop-up. In order to achieve this, I implemented the following code in one of my JS files.

 var str = Request.ExpDate;
        var x = '/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/';
        var patt = new RegExp(x);
        var res = patt.test(str); 

If res returns false, I intend to show a message. However, the issue lies in the fact that it returns false for all dates that are actually in the correct format.

Could you kindly explain why the regexp works correctly with ng-pattern but does not function properly within the JS function?

Answer №1

Your regular expression consistently returns a value of false because you included regex delimiters within the pattern while initializing it with a constructor notation (new RegExp(var)).

You can simplify this by initializing the RegExp using a regular literal, like so: /.../:

var str = Request.ExpDate;
var patt = /((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/;
var res = patt.test(str);

However, there seems to be some issues with your current regex pattern. Here is a corrected version:

/^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/

I have removed unnecessary {1} limiting quantifiers and eliminated any stray commas inside character classes like [1,2] and

[0,1]</code which could affect the results. Further refinement could involve removing redundant groups or converting them to non-capturing, but those changes are mainly cosmetic.</p>

<p>Check out this sample:</p>

<p><div>
<div>
<pre class="lang-js"><code>var str = "2992/10/31";
var patt = /^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/;
var res = patt.test(str);
document.write(res);

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

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

Converting yard values to meter values using AngularJS: A comprehensive guide

My task is to convert meter values to yard using two dropdowns. The first dropdown contains various values, while the second dropdown has "meter" and "yard" options. If "meter" is selected in the second dropdown, the values in the first dropdown remain unc ...

Having trouble locating module '@mdx-js/mdx' in Gatsby forest

Since the most recent update today, I've been encountering this error. There is no MDX being used in my project at all.. When running npm run develop, this issue arises. Does anyone have any insights on this? internal/modules/cjs/loader.js:979 thro ...

Can JSON encoding in a URL pose a risk of XSS attacks?

To ensure my application has URL-friendly capabilities, I am storing its context as a JSON within the URL. This results in something like: http://mysite.dev/myapppage/target#?context={%22attr1%22%3A{%22target_id-0%22%3A{%22value%22%3A%223%22%2C%22label%2 ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

"Exploring the possibilities of RSelenium and Javascript together

While I have a strong understanding of R, my knowledge in javaScript and other languages is very limited. My goal is to access information from a publicly-available data set found here: . Specifically, I have a list of postal codes formatted as 'A1A1A ...

When hovering over the bootstrap dropdown, the main dropdown remains a clickable link

How can I create a bootstrap dropdown menu that activates on hover, while still allowing the main button to link to a different page when clicked? Below is the HTML code: <div class="body-wrap"> <div class="container"> <nav class="navbar n ...

Automatically retrieve the generated PDF file upon completion (Node.js and Express)

I've been utilizing the node module html-pdf to seamlessly convert my HTML into PDF format. The conversion process goes smoothly, but I'm encountering difficulties when it comes to downloading the file once it's been generated. Below is the ...

Navigating through history using the pushState method and incorporating back and forward buttons

I am trying to implement back and forward buttons functionality with this ajax method The code is working well, and the URL in the browser is changing as expected However, when I click on the back and forward buttons, nothing happens (function(){ ...

What is the best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

An issue of "SignatureDoesNotMatch" arises while trying to send an email using Node AWS SDK for the Simple Email Service

I am facing an issue while attempting to send an email using the @aws-sdk/client-ses SDK in Node. The error I encounter is: SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access ...

performing a request to Axios API with the inclusion of ${item} within the URL

I am having trouble with calling axios in Vuetify due to backticks and ${} within the URL. I believe I need to convert it into JSON format, but my attempts have been unsuccessful. Could you please provide an explanation? Here is the code snippet. Whenever ...

Issue with using bind(this) in ajax success function was encountered

In my development process, I utilize both react and jQuery. Below is a snippet of the code in question. Prior to mounting the react component, an ajax request is made to determine if the user is logged in. The intention is for the state to be set when a ...

site.js problem

Recently, I decided to create my very own CS:GO gambling website. After successfully setting it up on my localhost using VPS, I moved on to getting a domain and finalizing everything. However, when attempting to run site.js, an error message popped up: [e ...

retrieving the parent of the a tag from a jquery form

When using the jQuery code below: $('#trade-offer form').on("submit", function(event) { event.preventDefault(); var stock = $(this).closest('.allloopedover'); console.log(stock); return; $.ajax({ url: ajaxur ...

Utilizing jQuery/Ajax to send an ID parameter to a PHP script

This code is where the user interacts. <html> <head> <title></title> <script src="jquery-1.9.1.js"></script> <script src="jquery.form.js"></script> </head> <body> <?php include 'con ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

Change the local date and time to UTC in the format of yy:mm:dd H:M

I must change the date format from local time to UTC or ISO as yy:mm:dd H:M, or calculate the difference between local date times with 03:30 as yy:mm:dd H:M 2016-10-22T04:30:00.000Z convert this to 2016-10-22T01:00:00.000Z ...

Querying for the presence of an ObjectId in an array in Mongoose

I'm developing a Node.js project that involves two models: User and Project. Below is the Schema for the Project model: const ProjectSchema = new mongoose.Schema({ name: { type: String, maxlength: 50, required: true, } ...

Encountered a TypeError with mongoose: The function specified is not recognized as a valid function when attempting to create a new mongoose instance

I'm currently developing a web application using the MEAN stack, and I've encountered an issue with my mongoose instance that's giving me a headache. Let me share parts of my code: my route const express = require('express'); co ...