如何使用reactjs在表单中添加动态验证 [英] how to add dynamic validation in form using reactjs

查看:33
本文介绍了如何使用reactjs在表单中添加动态验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的演示应用程序中使用 ant design.我想在我的应用程序中添加手机号码的动态验证.

在我的表单中有两个字段

  1. 选择字段
  2. 输入框

我想在mobileselect field时在输入字段中添加验证(手机号码应该是10位数字).换句话说,我想添加<强>输入字段上的手机号码仅当用户从选择框中选择手机

jsx

import React, { useState } from "react";import { Form, Icon, Input, Button, Select } from "antd";const { 选项 } = 选择;const SearchForm = props =>{const [mobileValidation, setMobileValidation] = useState(false);const [isOptionSelected, setIsOptionSelected] = useState(false);const { getFieldDecorator, getFieldsError } = props.form;const handleSubmit = e =>{e.preventDefault();移动验证&&props.form.validateFields({ force: true });};const handleChange = value =>{setIsOptionSelected(true);setMobileValidation(value === "手机号");};const 规则 = mobileValidation?[{ required: true, message: "请输入一个数字!"},{ 模式:/^[2-9]{2}\d{8}$/,消息:请输入 10 位数字!"}//{ pattern:/^\d{10}$/, message: "请输入 10 位数字!"}]: 空值;返回 (<div style={{ height: 80, display: "flex", justifyContent: "flex-end" }}><Form layout="inline" onSubmit={handleSubmit}><表单.项目>{getFieldDecorator("searchBy", {//initialValue: this.props.transactionEditableMode ?this.props.transactionEditableModeData.from : '',规则:[{ required:true,消息:请选择您的发件人!"}]})(<选择样式={{ 宽度:180 }}占位符="选择一个选项"onChange={handleChange}>{[{文字:咖啡馆编号",价值:咖啡馆"},{ 文字:手机号",值:手机号"}].map(i => {返回 (<Option key={i} value={i.value}>{i.text}</选项>);})})}</Form.Item><表单.项目>{getFieldDecorator("value", {规则})(<输入样式={{ 宽度:180 }}//prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}占位符=搜索一个数字"名称=输入"/>)}</Form.Item><表单.项目><Button type="primary" htmlType="submit">搜索</按钮>{!isOptionSelected &&<h3>选择一个选项</h3>}</Form.Item></表格>

);};const WrappedSearchForm = Form.create({ name: "search_form" })(SearchForm);导出默认 WrappedSearchForm;

这就是你要找的吗?告诉我

旁注:阅读validateFields()

I am using ant design in my demo application. I want to add dynamic validation of mobile number in my application.

In my form there two field

  1. select field
  2. input field

I want to add validation in the input field when select field in mobile(mobile number should be 10 digits).in other words I want to add validation of mobile number on input field only when user select mobile from select box

https://ant.design/components/form/

here is my code https://codesandbox.io/s/holy-voice-o4wbj

<Form.Item>
          {getFieldDecorator("value", {
            rules: [
              { required: true, message: "Please input search value!" },
              { pattern: /[2-9]{2}\d{8}/, message: "Please input !" }
            ]
          })(
            <Input
              style={{ width: 180 }}
              // prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}
              placeholder="searchValue"
            />
          )}
        </Form.Item>

can we add this validation ?

解决方案

You need to set rules as per some conditions like so:

 const rules = mobileValidation
    ? [
        { required: true, message: "Please input a number!" },
        { pattern: /^[2-9]{2}\d{8}$/, message: "Please input 10 digit number!" }
      ]
    : null;

Since you need only 10 digit number, you need to add ^ at the start and $ at the end of the regex pattern i.e. /^[2-9]{2}\d{8}$/

jsx

import React, { useState } from "react";
import { Form, Icon, Input, Button, Select } from "antd";

const { Option } = Select;
const SearchForm = props => {
  const [mobileValidation, setMobileValidation] = useState(false);
  const [isOptionSelected, setIsOptionSelected] = useState(false);

  const { getFieldDecorator, getFieldsError } = props.form;

  const handleSubmit = e => {
    e.preventDefault();

    mobileValidation && props.form.validateFields({ force: true });
  };
  const handleChange = value => {
    setIsOptionSelected(true);
    setMobileValidation(value === "mobile no");
  }; 
  const rules = mobileValidation
    ? [
        { required: true, message: "Please input a number!" },
        { pattern: /^[2-9]{2}\d{8}$/, message: "Please input 10 digit number!" }
        // { pattern: /^\d{10}$/, message: "Please input 10 digit number!" }
      ]
    : null;

  return (
    <div style={{ height: 80, display: "flex", justifyContent: "flex-end" }}>
      <Form layout="inline" onSubmit={handleSubmit}>
        <Form.Item>
          {getFieldDecorator("searchBy", {
            // initialValue: this.props.transactionEditableMode ? this.props.transactionEditableModeData.from : '',
            rules: [{ required: true, message: "Please select your From!" }]
          })(
            <Select
              style={{ width: 180 }}
              placeholder="Select a option"
              onChange={handleChange}
            >
              {[
                { text: "Caf Nos", value: "cafs" },
                { text: "mobile no", value: "mobile no" }
              ].map(i => {
                return (
                  <Option key={i} value={i.value}>
                    {i.text}
                  </Option>
                );
              })}
            </Select>
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator("value", {
            rules
          })(
            <Input
              style={{ width: 180 }}
              // prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}
              placeholder="search a number"
              name="input"
            />
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            Search
          </Button>

          {!isOptionSelected && <h3>Select an option</h3>}
        </Form.Item>
      </Form>
    </div>
  );
};

const WrappedSearchForm = Form.create({ name: "search_form" })(SearchForm);

export default WrappedSearchForm;

Is that what you were looking for? let me know

Side note: Read about validateFields()

这篇关于如何使用reactjs在表单中添加动态验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆