簡體   English   中英

如何在反應中從密碼驗證中刪除空格

[英]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}$

請注意如何將所有前瞻組合為一個以使正則表達式更短且更易於閱讀。

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM