How to validate form input fields using Ant design framework in react application - reactjs

I am trying to validate the form input field with decimal values, if the entered value is not number or decimal it should show error message, so far I have tried the below code example which is not validating characters and special character.
I would like to show error message when user enters, any other character than number and decimal
function position() {
const { dispatch } = useContext(store);
const [isDisable, setCheckBoxDisable] = useState(false)
const onApply = (values) => {
console.log('Success:', values);
dispatch({
type: "updateGPSCoordinates",
latitude: values.latitude,
longitude: values.longitude,
altitude: values.altitude
});
};
return (
<div>
<div className="homepage-widget-header">
<Form
{...layout}
className="gps-coordinates-form"
onFinish={onApply}
>
<Form.Item
label={GpsConstants.LATITUDE}
name="latitude"
initialValue="25.328380"
rules={[
{
required: true,
message: 'Please enter latitude!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label={GpsConstants.LONGITUDE}
name="longitude"
initialValue="51.435989"
rules={[
{
required: true,
message: 'Please enter longitude!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label={GpsConstants.ALTITUDE}
name="altitude"
initialValue="0.0"
rules={[
{
required: true,
message: 'Please enter altitude!',
},
]}
>
<Input />
</Form.Item>
</div>
</div>
)
}
export default GPSPosition
Thanks in advance
Appreciate quick help

Related

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

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;

Display an error if the password and login are incorrect in Form. Antd React

The task is as follows, when you press the LOGIN button, a request is sent to the server with a password and login, if they are incorrect, then under the password entry line you need to display the corresponding error and all input fields should be highlighted in red.
How can you achieve this?
I tried to do it for a very long time using built-in validators in Form.Item . So, since I don't need to worry about changing the color of input fields, the validator does it itself, but I got confused about these validators and I got an infinite loop.
Here is some of the code for the Login page.
export const LoginPage = () => {
const { dispatch } = useAuthContext()
const onFinish = (values: any) => {
APIs.requestLogin(values.username, values.password, false)
.then((response: any) => {
dispatch({ type: SIGN_IN, payload: response.data })
})
.catch(() => {
console.log('error')
})
}
return (
<div className={classes.root}>
<div className={classes.container}>
<Form
className={classes.form_container}
name="normal_login"
initialValues={{ remember: true }}
onFinish={onFinish}
>
<Form.Item
className={classes.form_input}
name="username"
rules={[{ required: true, message: 'Please enter your username!' }]}
>
<Input
autoFocus={true}
className={classes.input_style}
placeholder="Username"
prefix={<UserOutlined className="site-form-item-icon" />}
/>
</Form.Item>
<Form.Item
className={classes.form_input}
name="password"
rules={[{ required: true, message: 'Please enter your password!' }]}
>
<Input.Password className={classes.input_style} placeholder="Password" prefix={<LockOutlined />} />
</Form.Item>
<Form.Item className={classes.form_submit}>
<Button className={classes.form_button_submit} type="primary" htmlType="submit">
LOGIN
</Button>
</Form.Item>
</Form>
<div className={classes.image} />
</div>
</div>
)
}

Antd form doesn't identify input values

I have created my react form with antd. I have added antd validation for the form. But my form doesn't know whether I have filled the form or not. Whenever I filled the form and submitted it, it doesn't call onFinish method. Instead it fails and calls onFinishFailed method and gives me validation error messages.
I have created it in correct way according to my knowledge. But there is something missing I think. Here's my code.
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const history = useHistory();
const [form] = Form.useForm();
const layout = {
labelCol: { span: 4 },
wrapperCol: { span: 8 },
};
const onChangeName = (e) => {
setName(e.target.value);
console.log(name);
}
const onAddCategory = (values) => {
let req = {
"name": values.name,
"description": values.description
}
postCategory(req).then((response) => {
if (response.status === 201) {
message.success('Category created successfully');
history.push('/categorylist');
}
}).catch((error) => {
console.log(error);
message.error('Oops, error occured while adding category. Please try again');
});
}
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
console.log('State:', name, description);
};
return (
<React.Fragment>
<Form
form={form}
name="control-hooks"
onFinish={onAddCategory}
onFinishFailed={onFinishFailed}
{...layout}
size="large"
>
<Form.Item
name="name"
rules={[
{
required: true,
message: 'You can’t keep this as empty'
}, {
max: 100,
message: 'The category name is too lengthy.',
}
]}
>
<label>Category name</label>
<Input
placeholder="Category name"
className="form-control"
value={name}
onChange={onChangeName}
/>
</Form.Item>
<Form.Item
name="description"
rules={[
{
required: true,
message: 'You can’t keep this as empty'
}, {
max: 250,
message: 'The description is too lengthy',
}
]}
>
<label>Description</label>
<Input.TextArea
placeholder="Description"
className="form-control"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</Form.Item>
<Form.Item shouldUpdate={true}>
<Button
type="primary"
htmlType="submit"
className="btn btn-primary"
>
Add category
</Button>
</Form.Item>
</Form>
</React.Fragment>
)
In this form I have managed state using hooks. In onFinishFailed method I have logged my input values with state and they have values. But form doesn't identify it.
How do I resolve this. Please help.
I found the issue. Here I had added label inside form item. It was the reason for the unexpected behavior. Once I took the label outside the form item problem was solved.
<label>Category name</label>
<Form.Item
name="name"
rules={[
{
required: true,
message: 'You can’t keep this as empty'
}, {
max: 100,
message: 'The category name is too lengthy.',
}
]}
>
<Input
placeholder="Category name"
className="form-control"
value={name}
onChange={onChangeName}
/>
</Form.Item>

form.isFieldValidating not working in ant Design

i'm using next js
const [form] = Form.useForm();
const onFinishFailed = ({ values }) => {
console.log("email-status",form.isFieldValidating('email'),form.getFieldsError())
console.log("failed",values);
};
<Form
{...layout}
layout="vertical"
name="basic"
form = {form}
initialValues={{ email: "",password: "",remember: true,}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
name="email"
label="E-mail"
rules={[
{
type: 'email',
message: 'The input is not valid E-mail!',
},
{
required: true,
message: 'Please input your E-mail!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="password"
label="Password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
>
<Input.Password />
</Form.Item>
<Form.Item >
<Button type="primary" htmlType="submit">
Register
</Button>
</Form.Item>
Now when I type a valid email and doesn't enter a password and click on Register button
a) I'm getting 'Please input your password!',and not getting any error displayed under email input box // which is expected
b) Since i haven't entered any password on clicking the registered button
"onFinishFailed " function is being executed // so far so good
c) But in console I'm getting the output as
email-status, false, []
It should be email-status , true, [ ] right...

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