如何实现正则表达式以对更改事件做出反应?



我正在创建表单验证,我的输入之一是type='text'但我需要允许用户只写 0-9 的数字和最大数字长度 9。我可以在传递给状态之前传递任何正则表达式以消除输入值中的字母吗?

const handleChangeData = ({currentTarget}, key) => {
let val = currentTarget.value;
if (currentTarget.name === 'phone') {
const regex = /d+/;
val.match(regex);
changeData(prevState => {
return {...prevState, [key]: val};
});
}
// ... more code here
}

我不想使用type=number,也不能使用patters因为我有自己的错误弹出窗口。

.html:

<div className="form-control">
{errors.phone && (
<div style={{left: '-275.38px'}} className="error">
{errors.phone}
</div>
)}
<label htmlFor="phone">
<i className="fas fa-phone-alt"></i>
</label>
<input
value={data.phone}
id="phone"
name="phone"
onKeyPress={handleKeyPress}
onChange={e => handleChangeData(e, 'phone')}
type="text"
placeholder="Numer telefonu"
/>
</div>

您必须处理onKeyPress事件。

使用以下代码处理验证。

const validateNumber = (evt, regex) => {
var theEvent = evt || window.event;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}

调用上述方法onKeyPressinput元素

onKeyPress = (e) => { validateNumber(e, /[0-9]|./) }

希望这对你有用!

const handlePhoneChange = ({ currentTarget, key, keyCode }) => {
// Since this will trigger on every key, we only need to check
// if the key that was pressed is a digit.
// We could use a regexp on the value.
// Or check the key
// Or check the keyCode

// 1) RegExp
// We test that between the beginning and the end of the value, there are between 1 and 9 digits
const is_valid = /^d{1,9}$/.test( currentTarget.value );

// 2) key
// const is_valid = [0123456789].includes( key ) && currentTarget.value.length <= 9;

// 3) keyCode
//const is_valid = keycode >= 96 && keyCode <= 105 && currentTarget.value.length <= 9;;

// Update the state. If the typed character is a valid digit
// the new state is the full value
// Else it remains the previous valid value, without the character just typed
changeData( prevState => ({
...prevState,
phone: is_valid
? currentTarget.value
: currentTarget.value.slice( 0, -1 )
}));
};
// Event binding mockup, this would do react for you through onKeyPress={handleKeyPress}
document.querySelector( '#phone' ).addEventListener( 'keyup', handlePhoneChange );
// changeData mockup, react would also do this for you
const changeData = reducer => {
const state = reducer();
document.querySelector( '#phone' ).value = state.phone;
};
<input id="phone" name="phone" placeholder="Numer telefonu" type="text" value="">

最新更新