简体   繁体   English

如何防止用户使用jsx在表单中粘贴特定的特殊字符(仅允许的字符包括(_-。)

[英]How to prevent a user pasting specific special characters (only allowed characters include (_ - .) in a form using jsx

I also want to limit the first character to just a number or a letter. 我也想将第一个字符限制为一个数字或一个字母。 This is what I have so far to prevent the user from typing in special characters: 到目前为止,这是我防止用户输入特殊字符的方法:

validate(event) {
    const keycode = event.keyCode || event.which || event.type === 'paste';
    const key = String.fromCharCode(keycode);
    const pattern = new RegExp('^[a-zA-Z0-9\\_\\.\\-]$');
    return pattern.test(key) ? key : event.preventDefault();
}
const validateMyField = (currentFieldValue, props) => {
    if (currentFieldValue.match(/^[a-zA-Z0-9\\_\\.\\-]+$/)) {
        return true;
    }
    return false;
};

const templateNameValidator = createValidator(
    validateMyField,
    'You are attempting to paste with characters that are not allowed. Please remove characters and try again. (special characters can only include "_","-",".")'
);
 <Field
    className="usaa-input"
    component={Textarea}
    label="Template Name"
    name="name"
    maxLength={128}
    minRows={1}
    placeholder="Enter Template Name..."
    validate={composeValidators(required, templateNameValidator)}
    onKeyPress={this.validate}
/>

It might be easier to use a controlled input. 使用受控输入可能会更容易。 This is where we get and set the value to and from the state. 这是我们获取状态值并将其设置为状态的地方。

this.state = {inputValue: ""}

...

validateBeforeInput(e){
    if(matches the chars we want){
        this.setState({inputValue: e.target.value})    
    }
}

...
<input 
    value={this.state.inputValue}
    onChange{validateBeforeInput} // where the magic happens
/>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM