3

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 ?

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.

4

1 回答 1

10

您需要使用正则表达式文字符号并锚定电子邮件正则表达式:

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

这是一个phoneRegEx修复:

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

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

于 2016-11-30T17:44:25.613 回答