簡體   English   中英

在(React + Material-ui)中的JSX文件中使用正則表達式

[英]Use Regular expression in JSX file in (React + Material-ui)

我正在嘗試使用RegEx進行基於材料UI表單的驗證。 我正在使用基於JS的正則表達式,但是它不起作用。 為什么呢

以下是我的template.jsx文件中的代碼段。 my-form只是對有形的material-ui組件的包裝。

import {myForm, TextField} from '@react-component/my-form';

export default (props) => {
 } = props;
   const emailRegex = new RegExp('/\S+@\S+\.\S+/');
    const phoneRegEx = new RegExp('/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-/\s\.]{0,1}[0-9]{4}$/');
    return (
<myForm>
  <TextField id="smsNumber" value={userInfo.smsNumber} name="smsNumberName" required requiredError="Mobile is a required field." validations={{matchRegexp:phoneRegEx}} validationErrors={{matchRegexp:'Enter a valid mobile.'}} onChange={changeSmsNumber} floatingLabelText={t('userProfile.mobile', "Mobile")} floatingLabelFixed={true} hintText={t('userProfile.mobile', "Mobile")}/>
</myForm>
   );
};

此代碼始終會顯示“輸入有效的手機”錯誤消息。

您需要使用正則表達式文字符號並錨定電子郵件正則表達式:

 const emailRegex = /^\S+@\S+\.\S+$/;
                    ^^            ^^

這是一個phoneRegEx修復程序:

const phoneRegEx = /^[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-/\s.]?[0-9]{4}$/;

請注意, {0,1}限制量與?相同? 1次或0次 )。 有沒有必要逃避點內[...]字符類,它已經匹配文字圓點在那里。

暫無
暫無

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

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