如果正则表达式字符串存储在单独的javascript文件中,正则表达式不起作用

问题描述 投票:0回答:1

我有一个正则表达式验证在表单中使用提供的密码,密码必须是6个字符长,1个大写,1个小写,1个数字和1个特殊字符。 以下是表单的反应组件:

import React from "react";
import { passwordRegex } from "./Constants";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      email: null,
      password: null,
      disableSubmitButton: true
    };
  }

  formData = {
    email: "",
    password: ""
  };

  componentWillUpdate(nextProps, nextState) {
    nextState.disableSubmitButton = !(nextState.email && nextState.password);
  }

  initializeFormData = () => {
    this.formData = {
      email: this.state.email,
      password: this.state.password
    };
  };

  verifyFormData = () => {
    if (!passwordRegex.test(this.formData.password)) {
      console.error("invalid password");
      return false;
    }

    return true;
  };

  submitForm = event => {
    event.preventDefault();
    const ifFromValid = this.verifyFormData();
    console.log(ifFromValid);
  };

  render() {
    this.initializeFormData();
    return (
      <form onSubmit={this.submitForm}>
        <br />
        <label htmlFor="email">Email </label>
        <input
          type="text"
          onChange={event => {
            this.setState({ email: event.target.value });
          }}
        />
        <br />
        <label htmlFor="password" name="password">
          Password
        </label>
        <input
          type="password"
          onChange={event => {
            this.setState({ password: event.target.value });
          }}
        />
        <br />
        <input type="submit" name="submit" id="submit"
          disabled={this.state.disableSubmitButton}
        />
      </form>
    );
  }
}

Constants.js

export const passwordRegex = new RegExp(
  "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$",
  "g"
);

问题: 表单验证在第一个submit上正常工作,然后在进一步的submit点击时,正则表达式表现异常。有时它进入if (!passwordRegex.test(this.formData.password))区块,有时不进入。

奇怪的是:如果我在verifyFormData()函数中为passwrodRegex创建局部变量,则相同的代码非常完美:

      verifyFormData = () => {
        const passwordRegex = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$","g");
        if (!passwordRegex.test(this.formData.password)) {
          console.error("invalid password");
          return false;
        }

        return true;
      };
javascript reactjs
1个回答
1
投票

我认为你的问题是,奇怪的是,'g'标志。

试试这个:

passwordR = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$","g");
console.log(passwordR.test('As!df2L$'));
console.log(passwordR.test('As!df2L$'));

输出会让你大吃一惊。无论如何,这让我感到惊讶。 (剧透,它是true false

现在来看看:JavaScript RegExp cant use twice?

标题是“当您使用g标志时,RegExp实例具有状态”。

最后,如果删除g标志,请查看代码是否按预期工作。

我也发现了这个,它有类似的信息:Why does a RegExp with global flag give wrong results?

© www.soinside.com 2019 - 2024. All rights reserved.