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

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>
)
}

Related

Setting the value of an input field in antd react JS

I want to set the value of a field based on what I have in the database. Make it ineditable but also want the ability for customers to copy that value. I am able to read the values on submit but I dont know how to set them initially. I am using this
form.setFieldsValue({
clientID: 'value from database',
});
but its not working.
const APIAccess = () => {
const [form] = Form.useForm();
const dbvalues = "some value from database"
form.setFieldsValue({
clientID: dbvalues,
});
const handleSubmit = (value) =>
{
const payload = {
"appName" : form.getFieldValue('appName') ,
}
return (
<Form
name="control-hooks"
form={form}
>
<Form.Item
label="App Name"
name="appName"
rules={[
{
required: true,
message: 'Please select an App Name!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label="Your Client ID"
name="clientID"
>
<Input.Group >
<Space>
<Input/>
<Tooltip title="copy your Client ID">
<Button icon={<CopyOutlined />} onClick={() => {navigator.clipboard.writeText(clientID)}}/> </Tooltip>
</Space>
</Input.Group>
</Form.Item>
<Form.Item
>
<Button type="primary" htmlType="submit" onClick={handleSubmit}>
Save
</Button>
</Form.Item>
</Form>)
You don't want to programmatically set each initial value. Instead, pass all the initial values to the Form component:
<Form
initialValues={{
clientID: some_client_id,
}}
/>

How to get error message by getFieldError in AntD Form?

I'm validating form with Ant Design but I have a problem with getFieldError(). I need to get the error messages by the field name of Form.Item but it not works.
Here's my code not works below:
...
<Form form={form} name="login_form" onFinish={onFinish} scrollToFirstError>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Password cannot be empty!',
},
]}
help='' // hide validating message.
>
<>
{({ getFieldError }) => console.log(getFieldError('password'))}
//it not logging anything when submit form trigger error
<Input.Password placeholder="Enter your password" />
</>
</Form.Item>
</Form>
How can I solved this problem?
Your console.log will invoke, every time your component renders, so you need to rerender your component whenever validation applies on the form. To handle this situation you can use render prop with Form component, like this:
function CustomFormItem({ error, ...other }) {
console.log(error)
return <Input.Password placeholder="Enter your password" {...other} />;
}
function MyForm() {
const [form] = Form.useForm();
const onFinish = (values) => {
console.log(values);
};
return (
<Form
form={form}
name="login_form"
onFinish={onFinish}
scrollToFirstError
>
{(values,formInstance) => {
return (
<>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Password cannot be empty!',
},
]}
help="" // hide validating message.
>
<CustomFormItem error={formInstance.getFieldError('password')} />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</>
);
}}
</Form>
);
}
Consider that with above implementation, render prop will call with every change on the form.
Use can use getFieldError(); like the code example below
Function as Child Component is not working perfectly inside <Form.Item> component as of now.
<Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
{(values, formInstance) => {
console.log(formInstance.getFieldError("password")[0]);
return (
<>
<Form.Item
name="password"
label="Password"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
</>
);
}}
</Form>

Ant Design v4. How to show the error message from custom validator in form

How to get the error message from the validator and show it in the form? I have 2 types of errors: "Please enter password" - if the field is empty and "Incorrect password" - when the password does not match. How to realize this?
export const LoginPage = ({ startLogin }) => (
<div>
<Form
name="normal_login"
initialValues={{ remember: true }}
onFinish={startLogin}
validateTrigger='onSubmit'
>
///////////////////////////////////THE CORE PART////////////////////////////////////////
<Form.Item
name="password"
rules={[{ required: true, message: 'Please enter password!' }, ({ getFieldValue }) => ({
//WHY THE MESSAGE ABOVE IS NOT SHOWN AT ALL?
validator(_, value) {
axios.get('users.json').then(({ data }) => {
if (condition) //do smth.
else if (condition) {
throw new Error("Incorrect password"); //<-- HOW TO SHOW THIS
}
});
}).catch(e => {console.log(e); return e});
},
}),]}
>
/////////////////////////////////////////////////////////////////////////////////////////
<Input.Password
className="input"
iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
placeholder="Password"
/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="login-form-button">
Log in
</Button>
</Form.Item>
</Form>
</div>
);```

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