最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use Regular expression in JSX file in (React + Material-ui) - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Nov 30, 2016 at 7:58 greengrassblueskygreengrassbluesky 3731 gold badge7 silver badges23 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 11

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

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

And this is a phoneRegEx fix:

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

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.

发布评论

评论列表(0)

  1. 暂无评论