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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…