Instructions for validating an input field with yup to ensure it does not begin with '-', '+', or '_'

Is there a way to validate user input using YUP and restrict values that begin with '-', '+', or '_'?

Thank you for your help!

name: Yup.string()
    .required()
    .min(5, 'Too short')
    .matches(/^[aA-zZ\s]+$/, "Only alphabets are allowed for this field ")
    .matches()//code for checking wheather it starts with '+','-','_' if it starts I need to show an error
    

If you could provide the regex pattern for the following criteria:

  1. Minimum length of 5 characters
  2. No special characters allowed
  3. Cannot start with '-', '_', or '+'

Answer №1

Ensure that your desired inputs are matching the regex /^[_\-\+]{1}.*/:

const startsWithSpecialChars = /^[_\-\+]{1}.*/;

console.log('"hello" ==> ', !!'hello'.match(startsWithSpecialChars));
console.log('"hel+lo" ==> ', !!'hel+lo'.match(startsWithSpecialChars));
console.log('"_hello" ==> ', !!'_hello'.match(startsWithSpecialChars));
console.log('"-hello" ==> ', !!'-hello'.match(startsWithSpecialChars));
console.log('"+hello" ==> ', !!'+hello'.match(startsWithSpecialChars));

Here's a breakdown of the regex:

  • ^ signifies the start of the string
  • [_\-\+]{1} denotes exactly one character of _, -, or + (hyphen and plus sign are escaped)
  • .* indicates any number of characters following underscore, hyphen, or plus symbol

Noteworthy is that "hello" and "hel+lo" do not match, while "_hello", "-hello", and "+hello" do.

It's worth mentioning that the second condition (

.matches(/^[aA-zZ\s]+$/, "Only alphabets are allowed for this field ")
) may not function as intended; reconsider its implementation.

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

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

Tips for incorporating MUI into your Redwood JS project

Trying to integrate MUI into Redwood JS has been a challenge for me. I attempted to run the following command in the project directory: yarn add @mui/material Unfortunately, an error message appeared in the console stating: An error Running this command w ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

Guide on preventing selection with beforeSelectionChange when using the select All checkbox in ng-grid

When the select All checkbox in the header is clicked, the beforeSelectionChange function is called with a rowItem array. Unfortunately, there doesn't seem to be an option to disallow selection. I need to disable the checkbox for certain rows based on ...

Unraveling the Mystery of CSS3 or JavaScript Sliders

I am currently developing a new website and I was intrigued by the slider effect on Apple and IBM's websites. For reference, you can check out how it works on sites like: and I noticed that the text and images slide in opposite directions, which se ...

Is there a problem with Framer Motion exit and AnimatePresence in Next.js?

Why isn't my exit prop or AnimatePresence working as expected? This is my custom variant: const imgVariant = { initial: { opacity: 0, y: -100, }, animate: { opacity: 1, y: 0, transition: { type: " ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

Can Angular JS apply the uppercase filter to a boolean value?

My Angular 1.4.12 binding looks like this: {{ mob.mobDataSettings[7].value | uppercase }} The first part is a boolean value from a JSON file, which can be either true or false. But when rendered in HTML, it is not showing up as uppercase (e.g. TRUE), in ...

Discover the indices of elements that, when their values are added together, equal x

I have an array with elements structured like this: var x = 17; var arr = [{ value:2, quantity: 4 }, { value:8, quantity: 1 }, { value:3, quantity: 3 }]; How can I identify the indexes of elements that would add up to equal the x number? For example, in ...

Why does my dialog box only open the first time and not the second time?

I have created my own custom dialog box using jQuery and it seems to be working fine initially. However, after closing it once, when I try to open it again nothing appears. Can anyone help me identify what's causing this issue? Below is the source co ...

Retrieve information from a JSON document

My project involves a bookStore with a list of books that I am working on. I am trying to extract all the book data from a JSON file and display them in a card view on a webpage. Although my code is error-free and seems to be functioning properly, the da ...

Enable direct download from external servers

I'm in search of a way to prompt a download (by right-clicking and selecting "save as") for both mp4 and flv files. The challenge is that these files are not hosted on my server, they are direct links from external websites. I have tried using .htacce ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

Locate the nearest span element and update its CSS class

On my page, there is a section with the following code: <h5 class="text-center" id="findStore" style="width:260px"> <a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId ...

Exporting key/value objects with React components as values in Typescript

I have a .tsx file where I need to export an object containing key/value pairs. Each value is going to be a React component used in another file. While I will have multiple key/value pairs, I'm focusing on just one at the moment. object.tsx import { ...

I am encountering a problem with the setState function, and receiving the error message: "Cannot read property 'setState' of null"

I need assistance with my code. There seems to be an issue, possibly a syntax error, but I am having trouble pinpointing it: import React, { Component } from 'react'; class Note extends Component { constructor(props) { super(props); t ...