Home > Back-end >  how can I restrict user to write character in input field in react
how can I restrict user to write character in input field in react

Time:02-05

how can i restrict user to write character in input field in react ?

The problem is when ever user try to submit a blog post with title contain character

server gives error . can not read a to Object , i could not fix the server

then i want try other solution . i want restrict user to not type character in title of the post

how can i do that ?

my input field code is . currently user can write any thing include persian alphabet and numbers and english alphabet and it just work fine , but how can i restrict user to write character in title

sorry for bad english

              <Input
                maxLength={70}
                type="text"
                dir="rtl"
                ref={titleRef}
                id="title"
                value={title}
                onBlur={(e) => setTitle((prev) => prev.trim())}
                onChange={(e) => setTitle(e.target.value)}
                required
              />

CodePudding user response:

You could try the to add to your Input component the "pattern" attribute, which is available on "input" elements natively:

    <input pattern="[^ ]*" />

This allows you to set custom messages when users enter incorrect characters, too!

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

CodePudding user response:

  const handleChange = event => {
    const result = event.target.value.replace(' ', '');
    setTitle(result);
  };

<Input
  maxLength={70}
  type="text"
  dir="rtl"
  ref={titleRef}
  id="title"
  value={title}
  onChange={handleChange}
  required
 />
  • Related