在密碼欄位中,如果我給“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>
</>
);
}
uj5u.com熱心網友回復:
通過使用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'),
});
uj5u.com熱心網友回復:
那是因為您正在匹配 using .which 也接受空格。
使用\S來代替:
^(?=.*?[A-Za-z0-9#!@$%^&*() =])\S{8,20}$
請注意如何將所有前瞻組合為一個,以使正則運算式更短且更易于閱讀。
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389363.html
標籤:javascript 反应 正则表达式 福米克
上一篇:使用記事本 附加現有字串
