简体   繁体   English

如何在反应中从我的姓名输入字段中过滤特殊字符和空格?

[英]How can I filter special characters and spaces from my name input fields in react?

I wish to share this code just in case someone might need to solve such a problem of filtering unwanted characters when doing forms in react.我希望分享此代码,以防有人在反应中执行 forms 时可能需要解决过滤不需要的字符的问题。 For extras, my code shows how to pass props to components inside Route.另外,我的代码展示了如何将道具传递给 Route 中的组件。 For simplicity, I have focused on only these two inputs and omitted other stuff such as the submit button and css data for styling those classNames and ids.为简单起见,我只关注这两个输入并省略了其他内容,例如提交按钮和 css 数据,用于设置这些类名和 id 的样式。

import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import SignupForm from "./components/SignupForm";

class App extends Component {
  constructor() {
    super();
    this.state = {
      firstName: "",
      lastName: "",
    };
    //Binding this to the functions used as they wouldn't just work if not bound
    this.changeFirstName = this.changeFirstName.bind(this);
    this.changeLastName = this.changeLastName.bind(this);
    this.lettersOnly = this.lettersOnly.bind(this);
  }

  changeFirstName(e) {
    this.setState({ firstName: e.target.value });
  }

  changeLastName(e) {
    this.setState({ lastName: e.target.value });
  }

  // Error handler functions

  lettersOnly(nameInput) {//Replacing all characters except a-z by nothing with this function
    let regex = /[^a-z]/gi; 
    nameInput.target.value = nameInput.target.value.replace(regex, "");
  }

  render() {
    return (
      <Router>
        <div className="App">
          <Route
            exact
            path="/"
            comp={SignupForm}
            render={() => (
              <SignupForm

                //SignupForm submit props
                changeFirstNameHandler={this.changeFirstName}
                firstNameValue={this.state.firstName}
                changeLastNameHandler={this.changeLastName}
                lastNameValue={this.state.lastName}

                // Error handlers
                nameCharacterFilter={this.lettersOnly}
              />
            )}
          />
            )}
          />
        </div>
      </Router>
    );
  }
}

export default App;

Below is the signup form, which is the child component in this aspect, and also a function component as opposed to its parent component:下面是注册表单,这是这方面的子组件,也是一个 function 组件,而不是它的父组件:

import React from "react";

export default function SignupForm(props) {
  return (
    <div className="container" id="signupForm">
      <h1>Signup Form</h1>
      <div className="form-div">
        <form>
          <input
            type="text"
            placeholder="First Name"
            onChange={props.changeFirstNameHandler}
            value={props.firstNameValue}
            onKeyUp={props.nameCharacterFilter}
            className="form-control formgroup"
          />

          <input
            type="text"
            placeholder="Last Name"
            onChange={props.changeLastNameHandler}
            value={props.lastNameValue}
            onKeyUp={props.nameCharacterFilter}
            className="form-control formgroup"
          />
        </form>
      </div>
    </div>
  );
}

NB: Welcome to improve this code, if you feel the need!注意:如果您觉得有需要,欢迎改进此代码!

I think you can improve you're code with this changes:我认为您可以通过以下更改改进您的代码:

  • Use the regex directly in the onChange event在 onChange 事件中直接使用正则表达式
  • Use only one method to update the values仅使用一种方法来更新值

Here is an example of what I mean: https://codesandbox.io/s/react-playground-forked-vreku?fontsize=14&hidenavigation=1&theme=dark这是我的意思的一个例子: https://codesandbox.io/s/react-playground-forked-vreku?fontsize=14&hidenavigation=1&theme=dark

Regards!问候!

Okay here is an improved code and much more cleaner.好的,这是一个改进的代码,更干净。 However, I have just omitted the React Router part to focus on functionality of the state and functions in this case.但是,我只是省略了 React Router 部分,专注于 state 的功能和本例中的功能。 I also want the user to see when they type an unwanted character that it actually typed but then just deleted on key up so I have created an independent function justLettersAndHyphen(nameField) from changeValue(event) that is triggered by onKeyUp .我还希望用户看到他们何时键入了一个它实际键入的不需要的字符,但随后在按键时删除了,所以我从由onKeyUp触发的changeValue(event)创建了一个独立的 function justLettersAndHyphen(nameField)

import React from "react";
import SignupForm from "./SignupForm";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      firstName: "",
      lastName: ""
    };

    this.changeValue = this.changeValue.bind(this);
    this.justLettersAndHyphen = this.justLettersAndHyphen.bind(this);
  }

  changeValue(event) {
    this.setState({
      [event.target.name]: event.target.value,
    });
  }

  // Error handler functions

  justLettersAndHyphen(nameField) {
    let regex = /[^a-z-]/gi;
    nameField.target.value = nameField.target.value.replace(regex, "");
  }

  render() {
    return (
      <SignupForm
        firstNameValue={this.state.firstName}
        lastNameValue={this.state.lastName}
        changeValueHandler={this.changeValue}
        nameCharacterFilter={this.justLettersAndHyphen}
      />
    );
  }
}

export default App;

Child component edited with name property added.添加了名称属性编辑的子组件。

import React from "react";

export default function SignupForm(props) {
  return (
    <div className="container" id="signupForm">
      <h1>Signup Form</h1>
      <div className="form-div">
        <form>
          <input
            name="firstName"
            type="text"
            placeholder="First Name"
            onChange={props.changeValueHandler}
            onKeyUp={props.nameCharacterFilter}
            value={props.firstNameValue}
          />

          <input
            name="lastName"
            type="text"
            placeholder="Last Name"
            onChange={props.changeValueHandler}
            onKeyUp={props.nameCharacterFilter}
            value={props.lastNameValue}
          />
        </form>
      </div>
    </div>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 和 JSX 中导入名称中带有特殊字符的 JS 文件? - How can I import a JS file with special characters in it's name in React and JSX? 如何从_source访问带有特殊字符的字段? - How to access fields with special characters from _source? 如何将输入文本传递给我的 React 应用程序中的过滤器组件 - How can i pass the input text to the filter component in my React application 如何限制用户在反应 class 组件中的文本输入字段中输入数字或特殊字符 - How to restrict user from entering numbers or special characters in to text input field in react class components React - 如何从多个输入中获取值并将它们发送到我的输入? - React - How can I get the values from my multiple input and send them to my input? 使用 react 中的 express-fileupload 时如何访问文本输入字段 - How can I access the text input fields when using express-fileupload from react 如何在反应中添加或删除输入字段 - How can I make an add or remove input fields in react 如何在React中有选择地删除动态添加的输入字段? - How can I selectively delete dynamically added input fields in React? 如何格式化名称具有特殊字符的数组(json 格式)中的元素? - How can I format an element in array (json format) which its name has special characters? 如何从 formik 上下文中以点表示法访问输入字段的原始名称? - How can I access the original names of my input fields, in dot notation, from formik context?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM