简体   繁体   English

防止 [az] 在 reactJS 的输入类型 tel 上输入

[英]Prevent [a-z] from being typed on input type tel on reactJS

I have an input type=tel component that Im trying to give some extra validation and prevent [az] from being typed and pasted on the input.我有一个input type=tel组件,我试图提供一些额外的验证并防止 [az] 被输入并粘贴到输入上。 So far I've used e.key and prop onKeyDown which i know I can prevent individual characters but i cant find the way to get [az] to work.到目前为止,我已经使用了e.key和 prop onKeyDown ,我知道我可以阻止单个字符,但我找不到让 [az] 工作的方法。 Im trying with a good example I found here in SO but Im not sure how to get it, tried adding regEx insted but no luck...我尝试用我在 SO 中找到的一个很好的例子,但我不知道如何得到它,尝试添加 regEx insted 但没有运气......

const PhoneNumberInput = ({value, onChange, valid, ...rest}) => {

const [phoneValid] = useState(["a", "b", "c"]); <--- I added in a state what I dont want to be inputed, tried with `/[a-z]$*` but I understood that it wouldnt work... 

  return (
    <Input
      className={classNames('form-control ', {
        'is-invalid': !valid,
      })}
      type="tel"
      value={value}
      onChange={onChange}
      onKeyDown={e => phoneValid.includes(e.key) && e.preventDefault()}
      valid={valid}
      {...rest}
    />
  );
};

I've tried adding: const [phoneValid] = useState(["az"]);我试过添加: const [phoneValid] = useState(["az"]); but I understood later that prop "onKeyDown" doesnt work that way... How can I do to get the [aA-zZ] blocked from being inputed ||但我后来明白道具“onKeyDown”不能那样工作......我该怎么做才能阻止输入[aA-zZ] || && pasted? &&粘贴?

UPDATED CODE:更新代码:

const PhoneNumberInput = ({value, onChange, valid, ...rest}) => {
  if(/(^$|^\d*$)/.test(value)) {
     console.log('entered value is number (or nothing i.e. empty input), do something.')
  } else {
    console.log('entered value is not a number - can be alphabet, space, special character, etc' )
  } <------ Im getting both states fired on console independent of number or letter

  return (
    <Input
      className={classNames('form-control ', {
        'is-invalid': !valid,
      })}
      type="tel"
      value={value}
      onChange={onChange}
      valid={valid}
      {...rest}
    />
   );
 };
if(/(^$|^\d*$)/.test(value)) {
 // entered value is number (or nothing i.e. empty input), do something.
} else {
 // entered value is not a number - can be alphabet, space, special character, etc 
}

Found a very nice and clean solution:找到了一个非常好的和干净的解决方案:

  const PhoneNumberInput = ({value, onChange, valid, ...rest}) => {
  value = value.replace(/[^0-9\+]/g, ''); <--- replace on the value 
  return (
    <Input
      className={classNames('form-control ', {
       'is-invalid': !valid,
      })}
      type="tel"
      value={value}
      onChange={onChange}
      valid={valid}
      {...rest}
    />
   );
 };

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

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