简体   繁体   中英

How can I allow only letters in React.js input form?

there is a form I created using react-hook-form. I want to check the character for the name input in this form.

I created Regex in pattern section, my control works,

在此处输入图像描述

but I want to prevent entering numbers and symbols . Just letter only (including Turkish characters)

在此处输入图像描述

How can I do that? Does the input mask library work? I would be glad if you help.

codes and output are available below. Thanks.

<FormInput
  capitalize={{ textTransform: 'capitalize' }}
  // control={control}
  style="full"
  id="name"
  type="text"
  name="name"
  gtagStart={gtagStart}
  label="Name*"
  onChangeFunc={keyEvent => {
    const { value } = keyEvent.target;
    const lowerCaseAll = value.toLowerCase();
    keyEvent.target.value = lowerCaseAll.charAt(0).toUpperCase() + lowerCaseAll.slice(1);
  }}
  register={register({
    required: {
      message: 'Required',
      value: true,
    },
    pattern: {
      message: 'Please enter valid name',
      value: /^[a-zA-Z\u00C0-\u017F]+(?:\s[a-zA-Z\u00C0-\u017F]+)*$/,
    },
  })}
  error={errors.name}
/>

EDIT: I found a solution. Thanks for everyone who helped to me for this question.

Solution: With regex, I specified the characters to be entered in the input, then I defined them in onChangeFunc. The function has both character control and capitalizes text.

onChangeFunc={keyEvent => {
                  const { value } = keyEvent.target;
                  const lowerCaseAll = value.toLowerCase();
                  const replaceAll = lowerCaseAll.charAt(0).toUpperCase() + lowerCaseAll.slice(1);
                  keyEvent.target.value = replaceAll.replace(/[^a-zA-ZşŞıİçÇöÖüÜĞğ\- ]/g, '');
                }}

add pattern like this:

 pattern: {
    value: /^[a-zA-Z ]*$/,
    message: "Please Enter a valid name",
 },

You ca use the following Regex Only valid for letters and spaces

^[a-zA-Z ]*$

Check it out and let me know..

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