如何在输入字段reactjs中设置输入字母数字值格式?
IT技术
html
reactjs
user-input
                    2022-07-31 08:40:27
                
            
        2个回答
            查看我的解决方案:
export const inputAlphaNumeric = (e, callback) => {
    const value = (e.target.value) ? e.target.value.replace(/[^0-9a-zA-Z]+/ig, "") : '';
    if (e.target.value !== value) {
        e.target.value = value;
    }
    if(typeof callback === 'function'){
        return callback(value);
    }
}
在 onChange 输入参数中添加函数:
<Form.Group>
    <Form.Label>Example</Form.Label>
    <Form.Control 
        type="text"
        defaultValue={""}
        onChange={(e) => inputAlphaNumeric(e, (value) => {
            // customize with your code
            this.setState({ custom: value  });
        })}
     />
</Form.Group>
结果:
您始终可以像这样使用 Regex 来评估传入的字符串。
onChangeAlphaNumericInput(e) {
  const value = e.target.value;
  const regex = /^[0-9a-zA-Z(\-)]+$/; //this will admit letters, numbers and dashes
  if (value.match(regex) || value === "") {
    this.setState({ inputValue: value });
  }
}
这将使您的输入防止写入任何不需要的特殊字符。
编辑:
该字段的 onBlur 验证
onBlurValidateFormat(e) {
  const value = e.target.value;
  const regex = /([a-zA-Z]{4})+-([0-9]{3})+([a-zA-Z]{2})+$/g;
  if (!value.match(regex)) {
    //Show an error message or put a warning text under the input and set flag to prevent form submit
  }
}
其它你可能感兴趣的问题

