How can i validate the name input with allow numbers - reactjs

Why the rules are not working? i am using antd inputs, now i want to validate the fields, what thing i need to do to use the rules for the inputs?
<Form form={form} onFinish={onFinish} onFinishFailed={onFinishFailed}
autoComplete="off">
<Form.Item className="form-item" label={'name'} rules={[
{
required: true,
message: 'Please input your name!',
},
]}>
<Input name='name' />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
submit
</Button>
</Form.Item>
</Form>
i want to validate if 'name' just have letters not numbers, how can i do that?

Try this:
<Form form={form} onFinish={onFinish} onFinishFailed={onFinishFailed}
autoComplete="off">
<Form.Item className="form-item" label={'name'}
rules={[
{
pattern: new RegExp(/^[a-zA-Z]*$/),
message: 'No Numbers Allowed'
},
{
required: true,
message: 'Please input your name!',
}
]}>
<Input name='name' />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
submit
</Button>
</Form.Item>
</Form>;

Related

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>

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...

ant design form async-validator warning

I am using antd forms and rules and when im submiting a form i get warnings like:
async-validator: ["Please enter username"].
I tried { suppressWarning: true } but it didn't work, the warning is not the same text in the rule its the default template text
antd: ^4.6.4
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
>
<Input.Password />
</Form.Item>
<Form.Item {...tailLayout} name="remember" valuePropName="checked">
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
As described on the async-validator page (https://github.com/yiminghe/async-validator)
At the entry point to your app you can do the following to disable the warning messages.
import Schema from 'async-validator';
Schema.warning = function(){};
For antd >4.20.0, use the following line in the App.jsx, after last import instruction...
global.ASYNC_VALIDATOR_NO_WARNING = 1;

antd forms - complex child elements of <Form.Item>

I have a antd form like this:
return(
<Form
{...layout}
form={form}
onFinish={onFinish}
>
<Form.Item
label="Bezeichnung"
name="name"
initialValue={resource ? resource.name : ""}
rules={[{ required: true, message: 'Bitte Bezeichnung eingeben.' }]}
>
<Input />
</Form.Item>
<Form.Item
label="Farbe"
name="color"
initialValue={resource ? resource.color : undefined}
>
<Input />
</Form.Item>
<ColorPickerButton
onColorChange={(color) => {
form.setFieldsValue({
color: color.hex
});
}}
/>
</Form>
);
As you can see here, i hav an extra button (independenly of the form) which acts as a color-picker. The chosen color is then used with
form.setFieldsValue({
color: color.hex
});
My question is now: Is there a more convenient way of putting together the <Input /> component with the <ColorPickerButton />component to use it that way:
<Form.Item
label="Farbe"
name="color"
initialValue={resource ? resource.color : undefined}
>
<ColorPickerInput />
</Form.Item>
Do you want some kinds of "auto binding" between Form.Item and ColorPickerInput? You can try to pass form and name to ColorPickerInput component, and call form.setFieldsValue({[name]: value}) within ColorPickerButton.onColorChange to update it.

Reset Radio.Group values onSubmit click for antd library

I am using ant-design library. There is useForm() hook to reset values.
All values are being reset to original values but not for Radio.Group.
How do I reset my radio button state to priority value from State?
const [priority, setPriority] = useState(2);
const [form] = Form.useForm();
const onSubmit = (values) => {
console.log('Received values of form: ', values);
form.resetFields();
}
<Form
form={form}
labelCol={{ span: 4 }}
wrapperCol={{ span: 14 }}
layout="horizontal"
initialValues={{ size: "large" }}
size={"large"}
onFinish={onSubmit}
>
<Form.Item
name="title"
rules={[{ required: true, message: 'Title is required!' }]}
label="Title">
<Input placeholder="Title" />
</Form.Item>
<Form.Item
name="content"
rules={[{ required: true, message: 'Content is required!' }]}
label="Content">
<Input.TextArea placeholder="Content" />
</Form.Item>
<Form.Item label="Switch" name="switch">
<Switch />
</Form.Item>
<Form.Item name="priority" label="Radio.Button">
<Radio.Group defaultValue={priority}
onChange={onPriorityChange}>
<Radio.Button value={2}>High</Radio.Button>
<Radio.Button value={1}>Medium</Radio.Button>
<Radio.Button value={0}>Low</Radio.Button>
</Radio.Group>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
I added priority to the initialValues and it worked.
Refer this.
https://codesandbox.io/s/elegant-agnesi-9vp4x?file=/src/App.js

Resources