当前位置: 首页 > article >正文

【React】实现TagInput输入框,可以输入多个邮箱并校验是否合法

背景

需要实现一个类似Select组件的tags模式的输入框,输入一个邮箱后,回车,会显示成tag样式,也可以删除每一个tag。

实现

技术栈:react-tag-input-component + Antd

目前Antd没有提供现成的组件,可以使用react-tag-input-component,回车生成tag的时候进行校验邮箱是否合法,并显示错误提示

在进行表单提交的时候,也可以对tags进行非空和合法性校验。

EmailsFormInput/index.tsx:

import { Form, FormItemProps } from 'antd';
import { forwardRef, useImperativeHandle, useState } from 'react';
import { TagsInput, TagsInputProps } from 'react-tag-input-component';
import styles from './index.module.less';

interface Props {
  formItemProps: FormItemProps;
  tagsInputProps: TagsInputProps;
}

const EmailErrorText = 'Please enter a valid email';
const EmailsEmptyErrorText = 'Please enter email';
const EmailReg = /^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(,[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})*$/g;

export const EmailsFormInput = forwardRef(({ formItemProps, tagsInputProps }: Props, ref: any) => {
  const [emailErrorTip, setEmailErrorTip] = useState<string>('');

  const handleValidateEmail = (emails: string[]) => {
    // 必填
    if (!emails?.length) {
      setEmailErrorTip(EmailsEmptyErrorText);
      return false;
    }
    // 邮箱格式是否正确
    if (!emails?.every((e) => new RegExp(EmailReg).test(e))) {
      setEmailErrorTip(EmailErrorText);
      return false;
    }
    return true;
  };

  useImperativeHandle(ref, () => ({
    // 暴露对emails的校验方法
    handleValidateEmail,
  }));

  return (
    // validateStatus 和 help 用于错误提示
    <Form.Item {...formItemProps} help={emailErrorTip} validateStatus="error" className={styles.tagInputFormItem}>
      <div className={styles.tagInputContainer}>
        <TagsInput
          placeHolder="Input email and enter to add more"
          classNames={{ tag: styles.tagContainer, input: styles.inputContainer }}
          {...tagsInputProps}
          onKeyUp={(e) => {
            if (e.key === 'Backspace') {
              // 删除操作的时候,需要清空错误提示
              setEmailErrorTip('');
            }
          }}
          beforeAddValidate={(tag: string) => {
            // 添加tag前对输入的字符进行校验
            if (tag && new RegExp(EmailReg).test(tag)) {
              setEmailErrorTip('');
              return true;
            }
            setEmailErrorTip(EmailErrorText);
            return false;
          }}
        />
      </div>
    </Form.Item>
  );
});

EmailsFormInput/index.module.less: 修改ui以适应Antd的设计风格

.tagInputFormItem {
  .tagInputContainer {
    div:first-child {
      padding: 1px 2px;
      --rti-main: rgb(36, 126, 252);
      border: 1px solid #ccc;
      min-height: 54px;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
    }
  }
  .tagContainer {
    background-color: rgba(0, 0, 0, 0.06);
    margin: 2px 4px 2px 0;
    height: 24px;
    button {
      height: 10px;
      width: 10px;
      font-size: 10px;
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .inputContainer {
    height: 28px;
    width: 40%;
    margin-left: 8px;
    color: rgba(0, 0, 0, 0.88);
  }
}

使用

<EmailsFormInput
  formItemProps={{
    name: 'approver_list',
    label: 'Approver(s)',
    rules: [
      {
        required: true,
        message: 'Approver',
      },
    ],
  }}
  tagsInputProps={{ value: approvers, onChange: setApprovers }}
  ref={approverEmailInputRef}
/>

在这里插入图片描述
在这里插入图片描述


http://www.kler.cn/a/538861.html

相关文章:

  • DeepSeek元学习(Meta-Learning)基础与实践
  • 【韩顺平linux】部分上课笔记整理
  • 学习 PostgreSQL 流复制
  • Redis 集群原理、主从复制和哨兵模式的详细讲解
  • 利用 Python 爬虫获取按关键字搜索淘宝商品的完整指南
  • 【AI日记】25.02.09
  • Agent论文阅读:NormEnforcement with a Soft Touch: Faster Emergence, Happier Agents
  • 阿里云服务器XShell连接启动java -jar xxx.jar后退出ssh,后端也退出,使用screen 亲测管用!
  • 【Jetson Nano安装gpu版pytroch1.7torchvision0.8.1 in python3.8 跑 Ultralytics YOLO】
  • 关于预训练后训练、LLM和视频大模型相关学习记录
  • 周报1.0
  • 鸿蒙音视频播放器:libwlmedia
  • 如何解决 Linux 文件系统挂载失败的问题
  • vue print 打印
  • 11.递归遍历、迭代遍历、统一迭代、层序遍历
  • Excel大数据量导入导出
  • React 生命周期函数详解
  • antd-react日期组件disabledDate不可选择的日期 (置灰)属性
  • Nginx进阶篇 - nginx多进程架构详解
  • SpringBoot速成(八)登录实战:未登录不能访问 P5-P8
  • Vue 3 + Vite + JS 项目中实现组件全局自动化注册的魔法,极致组件自动化注册方案,开发效率飙升300%。
  • linux 基础知识点之工作队列workqueue
  • (done) openMP学习 (Day9: 优化链表操作)
  • DeepSeek介绍,以及本地部署和API使用
  • 内容中台赋能人工智能技术提升业务创新能力
  • Jenkins 使用教程:从入门到精通