在(React + Material-ui)中的JSX文件中使用正则表达式 [英] Use Regular expression in JSX file in (React + Material-ui)

查看:486
本文介绍了在(React + Material-ui)中的JSX文件中使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用RegEx进行基于材料UI表单的验证.我正在使用基于JS的正则表达式,但是它不起作用.为什么 ?

I am trying to use RegEx to do material-ui form based validation. I am using my JS based Regex, but it does not work. Why ?

以下是我的template.jsx文件中的代码段. my-form只是对有形的material-ui组件的包装.

Below is the snippet from my template.jsx file. my-form is just a wrapper on the formsy material-ui component.

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

此代码始终会显示输入有效的手机"错误消息.

This code always gives 'Enter a valid Mobile' error message.

推荐答案

您需要使用regex文字符号并锚定电子邮件regex:

You need to use a regex literal notation and anchor the email regex:

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

这是一个phoneRegEx修复程序:

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

请注意,{0,1}限制量词与?相同( 1或0次出现).无需在[...]字符类中转义一个点,它已经在那里匹配了文字点.

Note that {0,1} limiting quantifier is the same as ? (1 or 0 occurrences). There is no need escaping a dot inside [...] character class, it already matches a literal dot there.

这篇关于在(React + Material-ui)中的JSX文件中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆