简体   繁体   中英

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

Expected Results:- It should not accept only empty space or special characters. But when entered with alphabets and it should accept all characters and space.

           <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>

Solutions: Check whether String contains Alphabets or not. If String only contains special characters or spaces throw an error, and if a string has alphabets then there is no need to check for spaces and special characters.

Here: I have used regex to check the 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>
  );
}

在此处输入图像描述

To add to @gadgetvala's answer, you can use the pattern attribute (for input elements):

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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