In password field if I give "Password@345" its accepted and right but if I give "Password @ 345" its also accepted but its should not accepted because condition is there is no whitespace, how to remove the whitespace that if I type password with whitespace it should give error.
import React from "react";
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
export default function DropDown() {
const SignupSchema = Yup.object().shape({
Password: Yup.string()
.matches(
"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#!@$%^&*() =]).{8,20}$",
`Should contains at least 8 characters and at most 20 characters\n
Should contains at least one digit\n
Should contains at least one upper case alphabet\n
Should contains at least one lower case alphabet\n
Should contains at least one special character which includes !@#$%&*() =^\n
Should doesn't contain any white space`
)
.required('password is required'),
});
return (
<>
<Formik
initialValues={{
Password: '',
}}
validationSchema={SignupSchema}
onSubmit={values => {
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="Password" placeholder="type password" autoFocus="true" autoComplete="off"/>
{errors.Password && touched.Password ? (
<div style={{color:"red"}}>{errors.Password}</div>
) : null}
<br/><br/>
<button type="submit" >Submit</button>
</Form>
)}
</Formik>
</>
);
}
CodePudding user response:
By using yup
you can define multiple match
on your schema, so in your issue, you can define a separate match to check if password contains space
or not and then apply other validation terms. like below example:
const SignupSchema = Yup.object().shape({
Password: Yup.string()
.matches(/^\S*$/, 'Whitespace is not allowed')
.matches(
'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#!@$%^&*() =]).{8,20}$',
`Should contains at least 8 characters and at most 20 characters\n
Should contains at least one digit\n
Should contains at least one upper case alphabet\n
Should contains at least one lower case alphabet\n
Should contains at least one special character which includes !@#$%&*() =^\n
Should doesn't contain any white space`
)
.required('password is required'),
});
CodePudding user response:
That's because you are matching using .
which also accepts whitespaces.
Use \S
instead:
^(?=.*?[A-Za-z0-9#!@$%^&*() =])\S{8,20}$
Note how all the lookaheads can be combined into one to make the regex shorter and easier to read.