繁体   English   中英

如何限制在输入 texbox 中仅输入空格和特殊字符。 当使用字母输入时,我们需要允许两者

[英]how to restrict ONLY space and special characters to be entered in the input texbox. We need to allow both when entered with alphabets

预期结果:- 它不应该只接受空格或特殊字符。 但是当使用字母输入时,它应该接受所有字符和空格。

           <div>
            <div className={createNewContainerStyles}>
                <p>Reason</p>
                <TextArea value={reason} placeholder='Add reason' showCount maxLength={250} onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
                    setReason(e.target.value)
                }}>
                </TextArea>
                <div>
                  <Button type="default" 
                          loading={loading} 
                          onClick={onClose}>Cancel
                  </Button>
                  <Button type="primary" disabled={!reason} loading={loading} onClick={onBlacklistRequest}>Add
                    </Button>
                </div>
            </div>
        </div>

解决方法:检查字符串是否包含字母。 如果 String 仅包含特殊字符或空格会引发错误,并且如果字符串包含字母,则无需检查空格和特殊字符。

这里:我使用正则表达式来检查字符串。

import React, { useState } from "react";

export function App() {
  const [reason, setReason] = useState("");

  const verifyInput = (value) => {
    // Check String contain alphanumeric characters or not
    if(/[a-zA-Z]/g.test(value)){
        setReason(value);
    } else {
        // Handle Erorr
    }
  };

  return (
    <div>
      <p>Reason</p>
      <textarea
        value={reason}
        placeholder="Add reason"
        maxLength={250}
        onChange={(e) => verifyInput(e.target.value)}
      />
    </div>
  );
}

在此处输入图像描述

要添加到@gadgetvala 的答案,您可以使用pattern属性(用于input元素):

<div>
    <div className={createNewContainerStyles}>
        <p>Reason</p>
        <input type="text" value={reason} pattern="^[a-zA-Z][^$]+" placeholder='Add reason' showCount maxLength={250} onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
            setReason(e.target.value)
        }}/>
        <div>
            <Button type="default" loading={loading} onClick={onClose}>Cancel
            </Button>
            <Button type="primary" disabled={!reason} loading={loading} onClick={onBlacklistRequest}>Add
            </Button>
        </div>
    </div>
</div>

暂无
暂无

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

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