How to Trim White Spaces from input field in ant-design form? - reactjs

I have a form with ant design. I want to add a rule for each input field that the user can't enter spaces to fill the input. (spaces forbidden)
I try this method { transform: (value) => value.trim() }but it doesn't work.
I appreciate your help.
<>
<Form.Item
label={t("forms.inputs.Name.label")}
rules={[
{
required: true,
message: t("forms.inputs.Name.rules.required"),
},
{
min: 3,
message: t("forms.inputs.Name.rules.minLength"),
},
]}>
<Input />
</Form.Item>
<Form.Item
label={t("forms.inputs.job.label")}
rules={[
{
required: true,
message: t("forms.inputs.job.rules.required"),
},
]}>
<Input />
</Form.Item>
<Form.Item
label={t("forms.inputs.Company.label")}
rules={[
{
required: true,
message: t("forms.inputs.Company.rules.required"),
},
]}>
<Input placeholder={t("forms.inputs.currentCompany.placeholder")} />
</Form.Item>
</>

Just write a custom validation rule:
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: "Required"
},
{
validator: (_, value) =>
!value.includes(" ")
? Promise.resolve()
: Promise.reject(new Error("No spaces allowed"))
}
]}
>
<Input />
</Form.Item>
For email validation, you can use the following regex pattern:
<Form.Item
label="Email"
name="email"
rules={[
{
required: true,
message: "Required"
},
{
pattern: /([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\"([]!#-[^-~ \t]|(\\[\t -~]))+\")#([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])/,
message: "Invalid email"
}
]}
normalize={(value, prevVal, prevVals) => value.trim()}
>
<Input />
</Form.Item>
DEMO

Instead of trimming onChange, do that in an onBlur callback:
formatInput = (event) => { const attribute = event.target.getAttribute('name') this.setState({ [attribute]: event.target.value.trim() }) }
or when you click enter
onKeyPress={(e) => {if (e.key === "Enter") {setValue(e.target.value.trim())} }}

you can do like this instead of using trim()
import React, { useState } from 'react';
import 'antd/dist/antd.css';
import { Form, Input } from 'antd';
const App = () => {
const [inputValue, setValue] = useState({input1: '', input2: '', input3: ''});
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const handleOnChange = (e) => {
let {value} = e.target;
let data = {...inputValue};
if (value.length && value[0] === ' ') {
data[e.target.name] = '';
setValue(data);
return;
}
data[e.target.name] = value;
setValue(data);
}
return (
<Form
name="basic"
labelCol={{
span: 8,
}}
wrapperCol={{
span: 16,
}}
initialValues={{
remember: true,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<>
<Form.Item
label={t("forms.inputs.Name.label")}
rules={[
{
required: true,
message: t("forms.inputs.Name.rules.required"),
},
{
min: 3,
message: t("forms.inputs.Name.rules.minLength"),
},
]}>
<Input name="input1" value={inputValue.input1} onChange={handleOnChange} />
</Form.Item>
<Form.Item
label={t("forms.inputs.job.label")}
rules={[
{
required: true,
message: t("forms.inputs.job.rules.required"),
},
]}>
<Input name="input2" value={inputValue.input2} onChange={handleOnChange} />
</Form.Item>
<Form.Item
label={t("forms.inputs.Company.label")}
rules={[
{
required: true,
message: t("forms.inputs.Company.rules.required"),
},
]}>
<Input name="input3" value={inputValue.input3} onChange={handleOnChange} placeholder={t("forms.inputs.currentCompany.placeholder")} />
</Form.Item>
</>
</Form>
);
};
export default App;

Related

Why the ant design select option doesnt save selected option?

I have developed a project with context crud. Everything is fine, only the select option does not work, that is, after any option is selected and added, the selected option does not appear in the edit section. What is the problem ?
I have error this : 'Cannot read properties of undefined (reading 'name')'
import React, { useState } from "react";
import { useContext } from "react";
import { GlobalContext } from "../../context/GlobalState";
import { useNavigate } from "react-router-dom";
import { NavLink } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import styles from "../ContactForm/Form.module.scss";
import { toast } from "react-toastify";
import { Checkbox, Button, Form, Input, Select, Radio } from "antd";
const Form1 = () => {
const { ADD_CONTACT } = useContext(GlobalContext);
const [contact, setContact] = useState({
id: uuidv4(),
name: "",
surname: "",
fatherName: "",
specialty: "",
email: "",
gender: "",
updatesNotification: "",
test: "",
});
const { Option } = Select;
const { name, surname, fatherName, specialty, email } = contact;
let history = useNavigate();
const onSubmit = () => {
if (contact) {
ADD_CONTACT(contact);
history("/contacts");
console.log(contact);
toast.success("Contact successfully added");
}
};
const selectOptions = [
{ label: "One", value: 1 },
{ label: "Two", value: 2 },
{ label: "Three", value: 3 },
];
return (
<>
<Form
onFinish={onSubmit}
className={styles.form}
name="myForm"
initialValues={{
remember: true,
}}
autoComplete="off"
labelCol={{
span: 2,
}}
wrapperCol={{
span: 16,
}}
>
<div className="row">
<Form.Item
label="Name"
rules={[{ required: true, message: "Please input your name!" }]}
>
<Input
placeholder="Enter Your Name"
value={name}
name="name"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
</div>
<Form.Item
label="Surname"
rules={[{ required: true, message: "Please input your surname!" }]}
>
<Input
placeholder="Enter Your Surname"
value={surname}
name="surname"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item
label="Father Name"
rules={[{ required: true, message: "Please input your surname!" }]}
>
<Input
placeholder="Enter Your FatherName"
value={fatherName}
name="fatherName"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item
label="Email"
rules={[{ required: true, message: "Please input your mail!" }]}
>
<Input
name="email"
placeholder="your mail"
value={email}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item
label="Specialty"
rules={[{ required: true, message: "Please input your specialty!" }]}
>
<Input
name="specialty"
placeholder="your specialt"
value={specialty}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item label='Category'>
<Select
onChange={(e)=>setContact({ ...contact, [e.target.name]: e.target.value })}
defaultValue='category'
value={contact.test}
name="test"
style={{
width: 120,
}}
>
{selectOptions.map((item) => (
<Option key={item.value} value={item.value}></Option>
))}
</Select>
</Form.Item>
<Form.Item label="Gender">
<Radio.Group
onChange={(e) =>
setContact({
...contact,
[e.target.name]: e.target.checked ? e.target.id : "",
})
}
name="gender"
rules={[{ required: true, message: "Please your gender!" }]}
>
<Radio
id="female"
value="Female"
checked={contact.gender === "female"}
>
Female
</Radio>
<Radio id="male" value="Male" checked={contact.gender === "male"}>
Male
</Radio>
</Radio.Group>
</Form.Item>
<Form.Item>
<Checkbox
name="updatesNotification"
checked={contact.updatesNotification === "update"}
id="update"
onChange={(e) =>
setContact({
...contact,
[e.target.name]: e.target.checked ? e.target.id : "",
})
}
>
I want to be notified of updates
</Checkbox>
</Form.Item>
<div className={styles.buttons}>
<Button type="primary" htmlType="submit">
Add contact
</Button>
<NavLink to="/contacts">
<Button danger>Cancel</Button>
</NavLink>
</div>
</Form>
</>
);
};
export default Form1;
onChange Event in Antd Select only gives the Selected Value, it will not return any event
So Modifying your code into below will fix your issue..
<Select
onChange={(e)=>setContact({ ...contact, test : e })}
defaultValue='category'
value={contact.test}
name="test"
style={{
width: 120,
}}
>
{selectOptions.map((item) => (
<Option key={item.value} value={item.value}></Option>
))}
</Select>

Change date format in antd <DatePicker />

I'm submitting a form to send data to my API that receives date in the format of YYYY-MM-DD but by default the DatePicker component keeps adding extra characters of time to the end of the date, for example when I enter a date for my date of birth field the value is stored in the format below
{
"date_of_birth":"2003-02-03T13:32:49.543Z"
}
I would prefer it to be just
{
"date_of_birth":"2003-02-03"
}
below is the code for the form and its submit function
const Demo = () => {
const [visible, setVisible] = useState(false);
const [form] = Form.useForm();
const showUserModal = () => {
setVisible(true);
};
const hideUserModal = () => {
setVisible(false);
};
const onFinish = values => {
console.log(JSON.stringify(values))
const userToken = localStorage.getItem(AUTH_TOKEN)
IndividualService.setToken(userToken)
IndividualService.postIndividual(values).then(resp => {
console.log(resp)
message.success('successfully added details for Individual plan')
}).catch(error => {
message.error('Error occured, plase try again', error.message)
})
};
const customFormat = value => `custom format: ${value.format("YYYY-MM-DD")}`;
return (
<Card title='Enter Customer details for individual plan'>
<Row justify='center'>
<Col span={20}>
<Form.Provider
onFormFinish={(name, { values, forms }) => {
if (name === 'userForm') {
const { basicForm } = forms;
const dependants = basicForm.getFieldValue('dependants') || [];
basicForm.setFieldsValue({
dependants: [...dependants],
...values
});
setVisible(false);
}
}}
>
<Form {...layout} name="basicForm" onFinish={onFinish} size='small'>
<Form.Item
name="first_name"
label="First Name"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="other_names"
label="Other Names"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true,
},
]}
>
<Select>
<Option value="MALE">male</Option>
<Option value="FEMALE">female</Option>
</Select>
</Form.Item>
<Form.Item
name="date_of_birth"
label="Date of Birth"
rules={[
{
required: true,
},
]}
>
<DatePicker format={customFormat} />
</Form.Item>
<Form.Item
name="blood_group"
label="Blood Group"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="residential_address"
label="Residential address"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="workplace_address"
label="Workplace address"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="additional_telephone_no"
label="Additional phone no."
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="NIN"
label="NIN"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="next_of_kin_name"
label="Next of kin name"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="next_of_kin_telephone"
label="next of kin phone."
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="next_of_kin_email"
label="next of kin email."
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="dependants"
label="Dependants List"
shouldUpdate={(prevValues, curValues) => prevValues.dependants !== curValues.dependants}
>
{({ getFieldValue }) => {
const dependants = getFieldValue('dependants') || [];
return dependants.length ? (
<ul>
{dependants.map((d, index) => (
<li key={index} className="user">
<Avatar icon={<UserOutlined />} />
<p>{d.first_name} - {d.relationship}</p>
</li>
))}
</ul>
) : (
<Typography.Text className="ant-form-text" type="secondary">
( <SmileOutlined /> No dependant yet. )
</Typography.Text>
);
}}
</Form.Item>
<Form.Item {...tailLayout}>
<Button htmlType="submit" type="primary">
Submit
</Button>
<Button
htmlType="button"
style={{
marginLeft: 8,
}}
onClick={showUserModal}
>
Add User
</Button>
</Form.Item>
</Form>
<ModalForm visible={visible} onCancel={hideUserModal} />
</Form.Provider>
</Col>
</Row>
</Card>
);
};
You can add the prop format to get the input in custom format, as
<DatePicker
format="YYYY-MM-DD"
/>
This will display the date in the format YYYY-MM-DD in the date picker.
To convert this to the required format you may need to format it in the onFinish , as:
const onFinish = values => {
console.log(JSON.stringify(values))
const userToken = localStorage.getItem(AUTH_TOKEN)
IndividualService.setToken(userToken)
values["date_of_birth"] = moment(values.date_of_birth).format("YYYY-MM-DD")
IndividualService.postIndividual(values).then(resp => {
console.log(resp)
message.success('successfully added details for Individual plan')
}).catch(error => {
message.error('Error occured, plase try again', error.message)
})
};

antd form field is not resetting for checkboxes

I have a antd form that consists of input and checkboxes.
antd : 4.16.0
react : 17.0.2
After using,
this.formRef.current.resetFields();
the input fields are getting reset but not the checkboxes.
Sample Code:
<Form
layout="vertical"
hideRequiredMark
initialValues={{
sunH: [
moment("00:00", "HH:mm"),
moment("00:00", "HH:mm"),
],
monH: [
moment("00:00", "HH:mm"),
moment("00:00", "HH:mm"),
],
}}
ref={this.props.formRef}
>
<Row gutter={16}>
<Col span={12}>
<Form.Item
name="pName"
label="Name"
rules={[
{
required: true,
message: "Please enter Name",
},
]}
>
<Input placeholder="Enter name" />
</Form.Item>
<Form.Item name="Mon" label="" valuePropName="checked">
<Text>Mon</Text>
</Form.Item>
</Col>
</Row>
</Form>
the form takes in a onCancel props, so onCancel,
this.formRef.current.resetFields();
log of this.formRef.current:
you can manually set radio fields value null in that function ...
all you have to do is ...
formRef.setFieldsValue(['label_name(Mon)'] : undefined)
try formRef.current.setFieldsValue if you cant't change using upper code.
for functional component you have to take the form reference that is binding using useForm() and you have to call setfield method same.
form.setFieldsValue(['label_name(Mon)'] : undefined )
ant.design/components/form/#components-form-demo-nest-messages Check the second example, they have well explained everything you need there
https://codesandbox.io/s/form-methods-antd-4-17-0-alpha-7-forked-ff1uf?file=/index.js:0-2953
Check this working example with checkbox
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input, Button, Select, Checkbox } from "antd";
const { Option } = Select;
const layout = {
labelCol: {
span: 8
},
wrapperCol: {
span: 16
}
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16
}
};
const Demo = () => {
const [form] = Form.useForm();
const onGenderChange = (value) => {
switch (value) {
case "male":
form.setFieldsValue({
note: "Hi, man!"
});
return;
case "female":
form.setFieldsValue({
note: "Hi, lady!"
});
return;
case "other":
form.setFieldsValue({
note: "Hi there!"
});
}
};
const onFinish = (values) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({
note: "Hello world!",
gender: "male"
});
};
return (
<Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
<Form.Item
name="note"
label="Note"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true
}
]}
>
<Select
placeholder="Select a option and change input text above"
onChange={onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) =>
prevValues.gender !== currentValues.gender
}
>
{({ getFieldValue }) =>
getFieldValue("gender") === "other" ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
) : null
}
</Form.Item>
<Form.Item
name="remember"
valuePropName="checked"
wrapperCol={{
offset: 8,
span: 16
}}
>
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={onFill}>
Fill form
</Button>
</Form.Item>
</Form>
);
};

Unexpected token (8:8) while parsing file

I'm using antd and I wanna use its registration Form in my project.
Note: Before adding this component my project (registration.js) was working correctly and I've just copied and pasted the antd component.
Here is my registration.js file:
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const AutoCompleteOption = AutoComplete.Option;
class RegistrationForm extends React.Component {
state = {
confirmDirty: false,
autoCompleteResult: [],
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
}
handleConfirmBlur = (e) => {
const value = e.target.value;
this.setState({ confirmDirty: this.state.confirmDirty || !!value });
}
compareToFirstPassword = (rule, value, callback) => {
const form = this.props.form;
if (value && value !== form.getFieldValue('password')) {
callback('Two passwords that you enter is inconsistent!');
} else {
callback();
}
}
validateToNextPassword = (rule, value, callback) => {
const form = this.props.form;
if (value && this.state.confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
}
handleWebsiteChange = (value) => {
let autoCompleteResult;
if (!value) {
autoCompleteResult = [];
} else {
autoCompleteResult = ['.com', '.org', '.net'].map(domain => `${value}${domain}`);
}
this.setState({ autoCompleteResult });
}
render() {
const { getFieldDecorator } = this.props.form;
const { autoCompleteResult } = this.state;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
const prefixSelector = getFieldDecorator('prefix', {
initialValue: '86',
})(
<Select style={{ width: 70 }}>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
);
const websiteOptions = autoCompleteResult.map(website => (
<AutoCompleteOption key={website}>{website}</AutoCompleteOption>
));
return (
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="E-mail"
>
{getFieldDecorator('email', {
rules: [{
type: 'email', message: 'The input is not valid E-mail!',
}, {
required: true, message: 'Please input your E-mail!',
}],
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Password"
>
{getFieldDecorator('password', {
rules: [{
required: true, message: 'Please input your password!',
}, {
validator: this.validateToNextPassword,
}],
})(
<Input type="password" />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Confirm Password"
>
{getFieldDecorator('confirm', {
rules: [{
required: true, message: 'Please confirm your password!',
}, {
validator: this.compareToFirstPassword,
}],
})(
<Input type="password" onBlur={this.handleConfirmBlur} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label={(
<span>
Nickname
<Tooltip title="What do you want others to call you?">
<Icon type="question-circle-o" />
</Tooltip>
</span>
)}
>
{getFieldDecorator('nickname', {
rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }],
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Habitual Residence"
>
{getFieldDecorator('residence', {
initialValue: ['zhejiang', 'hangzhou', 'xihu'],
rules: [{ type: 'array', required: true, message: 'Please select your habitual residence!' }],
})(
<Cascader options={residences} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Phone Number"
>
{getFieldDecorator('phone', {
rules: [{ required: true, message: 'Please input your phone number!' }],
})(
<Input addonBefore={prefixSelector} style={{ width: '100%' }} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Website"
>
{getFieldDecorator('website', {
rules: [{ required: true, message: 'Please input website!' }],
})(
<AutoComplete
dataSource={websiteOptions}
onChange={this.handleWebsiteChange}
placeholder="website"
>
<Input />
</AutoComplete>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Captcha"
extra="We must make sure that your are a human."
>
<Row gutter={8}>
<Col span={12}>
{getFieldDecorator('captcha', {
rules: [{ required: true, message: 'Please input the captcha you got!' }],
})(
<Input />
)}
</Col>
<Col span={12}>
<Button>Get captcha</Button>
</Col>
</Row>
</FormItem>
<FormItem {...tailFormItemLayout}>
{getFieldDecorator('agreement', {
valuePropName: 'checked',
})(
<Checkbox>I have read the agreement</Checkbox>
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit">Register</Button>
</FormItem>
</Form>
);
}
}
const WrappedRegistrationForm = Form.create()(RegistrationForm);
ReactDOM.render(<WrappedRegistrationForm />, document.getElementById('main'));
And this is my index.html file:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>React Project</title>
</head>
<body>
<div id="main"></div>
<script src="/build/bundle.js"></script>
</body>
</html>
I face with this error in my registration.js file:
Unexpected token (8:8) while parsing file
Line 8 refers to where we have state = {, how can I solve this problem?
Probably you are not using the right transpilers.
Declaring global variables in classes like your state = { ... } is only possible with ES7 (I believe). You are probably using a ES6 transpiler.
One fix would be changing your syntax to ES6. So you would have to declare you state like this:
class RegistrationForm extends React.Component {
constructor(props) {
super(props);
this.state = { ... };
}
// ...
}
ES6 also doesn't support declaring class methods with arrow syntax (myMethod = () => { ... }). You would have to change all of your methods to myMethod() { ... }
Another fix would be to download the right presets so babel (I'm guessing you are using babel) can transpile your ES7 syntax.

getFieldDecorator rules for password reset?

I'm trying to do a "field 2 does not match field 1" thing here (i.e. "passwords do not match).
There isn't much documentation on the available rules for the antd forms. They point at this project here.
Below is my current form:
const ResetPasswordForm = Form.create()(React.createClass({
getInitialState () {
return {
loading: false
};
},
handleSubmit(e) {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (err) {
failure();
}
if (!err) {
let newPassword = values.newPassword;
let repeatNewPassword = values.repeatNewPassword;
handleResetPassword(newPassword, repeatNewPassword, this.props.token);
}
});
},
render() {
const { getFieldDecorator } = this.props.form;
const newPasswordRules = [
{ required: true, message: 'Please input a new password!' }
];
const repeatNewPassword = [
{ required: true, message: 'Please repeat the new password!' }
];
return (
<Form onSubmit={this.handleSubmit} className="login-form">
<FormItem>
{getFieldDecorator('newPassword', { rules: newPasswordRules })(
<Input addonBefore={<Icon type="lock" />} type="password" placeholder="New password" />
)}
</FormItem>
<FormItem>
{getFieldDecorator('repeatNewPassword', { rules: repeatNewPassword })(
<Input addonBefore={<Icon type="lock" />} type="password" placeholder="Repeat new password" />
)}
</FormItem>
<FormItem>
<Button loading={this.state.loading} type="primary" htmlType="submit" className={css(styles.loginButton)}>
Reset Password
</Button>
</FormItem>
</Form>
);
}
}));
If anyone can point me in the right direction for creating a rule that checks that the first field value matches the second, that'd be awesome!
You can find it in this register form demo: https://ant.design/components/form/#components-form-demo-register
Please, follow these lines:
<Form.Item
name="password"
label="Password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
hasFeedback
>
<Input.Password />
</Form.Item>
<Form.Item
name="confirm"
label="Confirm Password"
dependencies={['password']}
hasFeedback
rules={[
{
required: true,
message: 'Please confirm your password!',
},
({ getFieldValue }) => ({
validator(rule, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject('The two passwords that you entered do not match!');
},
}),
]}
>
<Input.Password />
</Form.Item>

Resources