ASP.NET validation expression for allowing digits and certain characters such as "/" and "-"

I am trying to create an expression that will accept / and - characters, like this 123/12-125 (must accept / and -).

I attempted to write a ValidationExpression as follows: "^(\d*\/?\d*)^(\d*\-?\d*)$", but it did not work.

The '/' or '-' will be in the middle of the string with single occurrences multiple times. Both characters are optional.

For example:

12/321/1122122-9-666/9995

Answer №1

The regular expression "^(\d+([\/\-]\d+)+)$" is effective. I have personally tested and confirmed its functionality.

Answer №2

If you need to ensure that all required digits match:

"^(\\d{3}\\/\\d{2}\\-\\d{3})$"

If you require 123/12 and -125 is optional

"^(\\d+\\/\\d+)(\\-\\d+)?$"

and so on

In many programming languages, the backslash \ can be misinterpreted in regular expressions. To use it properly, you must double it as \\. For example, use \d +.

Additionally, use * for options that may or may not occur, and use + for mandatory occurrences.

Lastly, remember that ^ should only be used at the beginning of a "sentence". It can also be used within a group as a negation like [^ az], but be cautious as it accepts "anything that is not ...".

Test your regular expression here:

Robular

This tool will show you exactly what matches your expression.

You can also organize match groups like this:

"^(\d+([\/\-]\d+)+)$"

This pattern means:

  • It must begin with at least one digit
  • It should contain at least one occurrence of digit, /, or - followed by another digit
  • This structure can repeat indefinitely, but each repetition must include / or - followed by a digit

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

A guide on arranging and styling last names in an array in alphabetical order using JavaScript!

I created an array called moonwalkers and developed a function named alphabetizer to organize the names in alphabetical order with the last name appearing first. Although it functions correctly, I am seeking ways to enhance the code. For my reference, I ...

The JavaScript "sort()" method outlined in the Mozilla Documentation specifically created for the sorting of numbers

When it comes to sorting numbers in JavaScript, we can utilize the sort() function with a specific trick that yields perfect results. The tip for successful number sorting is as follows: [12, 2, 23, 3, 43, 54].sort(function (a, b) { return a - b ; } ) S ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

Create a user-friendly responsive tooltip in Javascript/jQuery with a convenient close

Looking to implement a tooltip feature that appears when a text box is focused on my responsive website, and disappears when it loses focus. Can anyone recommend the best JavaScript/jQuery library for this specific purpose? Here are my requirements: T ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

Using TypeScript, you can access the constructor of a derived type by calling it with the

In my TypeScript project, I am attempting to generate or duplicate a child object using a method within the base class. Here is my simplified code setup: abstract class BaseClass<TCompositionProps> { protected props: TCompositionProps; prot ...

Combining multiple storageStates in a playwright context for efficient loading

I am trying to load multiple storageStates into a single context in playwright, but I am facing some issues. When using the following code: const context = await browser.newContext({ storageState: "telegram.json",storageState: "google. ...

React and Lottie Animation seamlessly synchronized with scrolling movements

I utilized Bodymovin to create various animations and I am hoping to trigger the animation when the scroll reaches that specific point. I have been attempting to find a solution, but unfortunately, I have not been successful. Currently, I am using Gatsby ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

give parameters to a node function being exported

Script.js var routes = require('../controllers/routes.server.controller'); module.exports = function(app) { app.get('/',function(request,response){ return response.send("Welcome to the website"); }); app.route(' ...

Is the state mutated when using the .map() function to update it?

I am new to working with React and I am still struggling to understand state mutation. After reading multiple posts on this topic, I am finding it difficult to grasp the concept of state mutation. So, I have decided to seek clarification on this matter. ...

Is there a more straightforward method than using a recursive function to serialize a JavaScript object for an AJAX request?

Check out this function and helper I created for serializing a javascript object to send in an ajax request. While there may be more efficient solutions in libraries like jQuery, I couldn't find one specifically for a javascript object. /* @author Be ...

Having trouble toggling the dropdown submenu feature in a Vuejs application?

.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorial ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

What is the best way to display a specific object prop on a page after triggering the onChange() method from a selected

Looking to simplify some code that's become a bit overwhelming. My pizza order consists of arrays for size and price. I'm trying to update the price when a user selects a size, but I've been stuck on an issue with mapping pizzas from the ca ...

Efficiently transferring property values

In my current code, I have functions that retrieve specific properties from an object within an array. Since each object in the array has multiple properties, I find myself using separate functions to extract different properties. This approach is not eff ...

"Please ensure that the field values in MessageEmbed are not left empty" stated discord.js

I've been working on a Discord bot using node.js, and I've encountered an issue with my kick and ban commands. I've tried to incorporate Discord embeds, but I keep running into this problem. Can anyone assist me with this? Here is the code ...

Encountered error: Unable to access property 'value' as it is undefined while mapping in react components

element populateOptions() { return this.props.options.map((option, i) => ( <optgroup key={i} label={option.text}> {option.value.map((entry) => ( <option>{entry.text}</option> ))} </optg ...