如何从反应中的密码验证中删除空格

how to remove whitespace from password validation in react

在密码字段中,如果我给“Password@345”它被接受并且是正确的但是如果我给“Password@345”它也被接受但是它不应该被接受因为条件是没有空格,如何删除空格如果我用空格输入密码,它应该会出错。

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>
    </>
  );
}

通过使用 yup,您可以在您的架构上定义多个 match,因此在您的问题中,您可以定义一个单独的匹配项来检查密码是否包含 space,然后应用其他验证条款。像下面的例子:

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'),
});

那是因为您正在使用 . 进行匹配,它也接受空格。

改用\S

^(?=.*?[A-Za-z0-9#!@$%^&*()+=])\S{8,20}$

请注意如何将所有前瞻组合成一个以使正则表达式更短且更易于阅读。

Demo