'How do I not allow special characters and space in react hook using yup
Here's the code:
{
label: "Name",
name: "name",
placeholder: 'Name',
type: "text",
rule: yup.string()
.required('Name is a required field')
.matches(/^[a-zA-Z0-9]+$/, '* This field cannot contain white space and special character'),
},
What I'm trying to do is to restrict the input which does not allow any special characters and whitespace. also how to validate the input while typing in yup?
I tried to do like this:
!/^[a-zA-Z0-9]+$/
but I'm getting an error which is this
The argument of type 'boolean' is not assignable to parameter of type 'RegExp'.
Solution 1:[1]
You can use Formik and Yup to validate and disable the submit button based on the rules , but it will not help you restrict the input , you will need to handle that in onKeyUp / onKeyPress . Sandbox link to an example using Formik and Yup for validation for the email field and using onKeyPress to restrict only a-z and A-Z for the name field
https://codesandbox.io/s/vigilant-pike-lr5p2e?file=/src/App.js
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |