Two Antd forms, one component - reactjs

I have two antd forms within a single component. The first form is a register form where a user inputs various information (firstname, lastname, email, etc..) The submit button triggers a function to open a modal with another form for them to verify their phone number by generating a code that is texted to them. Once the code is typed and they hit verify, it verifies if it is the correct code - then i would like for it to register the user but I am having difficulties pulling in the values from the first form..
Is there a specific way to go about doing this? I thought maybe I could utilize useState and set the values to component level state but even that didnt work..
form
<Form
layout="vertical"
name="register-form"
initialValues={initialValues}
onFinish={handleVerification}
>
<Row gutter={ROW_GUTTER}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="firstName"
label="First Name"
rules={rules.firstName}
hasFeedback
>
<Input placeholder="Enter First Name" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="lastName"
label="Last Name"
rules={rules.lastName}
hasFeedback
>
<Input placeholder="Enter Last Name" />
</Form.Item>
</Col>
</Row>
<Row gutter={ROW_GUTTER}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="phone"
label="Phone Number"
rules={rules.phone}
hasFeedback
>
<Input placeholder="Enter Phone Number" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item name="city" label="City" rules={rules.city} hasFeedback>
<Select placeholder="Select City">
<Option value="Lancaster, PA">Lancaster, PA</Option>
</Select>
</Form.Item>
</Col>
</Row>
<Form.Item
name="email"
label="Email Address"
rules={rules.email}
hasFeedback
>
<Input placeholder="Enter Email Address" />
</Form.Item>
<Form.Item
name="password"
label="Password"
rules={rules.password}
hasFeedback
>
<Input.Password placeholder="Enter Password" />
</Form.Item>
<Form.Item
name="confirmPassword"
label="Confirm Password"
rules={rules.confirm}
hasFeedback
>
<Input.Password placeholder="Confirm Password" />
</Form.Item>
<Form.Item name="tos" valuePropName="checked">
<Checkbox>
I agree to the <Link to="/">Terms of Service</Link> and{' '}
<Link to="/">Privacy Policy</Link>.
</Checkbox>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block>
Register
</Button>
</Form.Item>
</Form>
<Modal
title="Account Verification"
centered
visible={modal}
onOk={() => setModal(false)}
onCancel={() => setModal(false)}
>
<p>
To finish registering, please enter the verification code we just sent
to your phone. If you didn't receive a code, make sure your entered
phone number is correct and sign up again. Your code will expire upon
closing this popup.
</p>
<Form layout="vertical" name="verify-phone-form" onFinish={onSubmit}>
<Form.Item name="enteredCode" label="Verify">
<Input placeholder="Enter Code" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block>
Verify
</Button>
</Form.Item>
</Form>
</Modal>
handleVerification
const handleVerification = async (values) => {
const { phone, email } = values;
setModal(true);
try {
const response = await postRegisterCheckDuplicate({ email, phone });
if (response.data.success) {
switch (response.data.message) {
case 0:
try {
const response = await dispatch(
attemptRegisterVerify({ to: phone })
);
console.log('handleVerification: ', response.message);
if (response.success) {
setGeneratedCode(response.message);
} else {
console.log(response.message);
}
} catch (error) {
console.log(error);
}
break;
case 1:
console.log('Email Address already in use.');
break;
case 2:
console.log('Phone number already in use.');
break;
case 3:
console.log('Email and Phone in use.');
break;
}
} else {
console.log(response.data.message);
}
} catch (error) {
console.log(error);
}
};
onSubmit
const onSubmit = (values) => {
const { enteredCode } = values;
if (generatedCode === enteredCode) {
try {
console.log('values :', values);
// dispatch(attemptRegister(values));
} catch (error) {
console.log(error);
}
} else {
console.log('Verification code incorrect');
}
};

You can create a form instance (hooks) and reference it to the first form so you can use the api of the instance. You can check more here antd FormInstance
const [registerForm] = Form.useForm();
const handleSubmit = (values) => {
const { enteredCode } = values;
console.log(registerForm.getFieldsValue());
//output is the values in the first form
};
<Form form={registerForm} layout="vertical" onFinish={handleVerification}>
...
</Form>
I created a small version of your work. See working code here:
You can also check this one antd control between forms

Related

form input not resetting with useState

I have a react bootstrap number form and state.
I would like to reset hours state to 0 after performing the button click and API POST transaction.
hours state updates just fine for the onChange function where I call setHours() in form and I'm using this strategy to reset form data on other components. Any ideas why I can't get it to work elsewhere after button click (i.e. in my try/catch block)??
const [hours, setHours] = useState(0);
// ...
const handleAddWorkItem = async (sprintId, date, hours) => {
try {
await addWorkItemToAirtable(sprintId, date, hours);
const workItems = await fetchWorkItemsByJobId(sprint.job.id);
setworkItems(workItems);
setHours(0); // not working
} catch (error) {
console.log({ error });
}
};
// ...
<Form>
<Form.Group
className="mb-2"
controlId="addTimeFormEmployee"
>
<Form.Label className="mb-0">
<strong>Employee:</strong>
</Form.Label>
<Form.Select
disabled
defaultValue={sprint.employee.id}
onChange={(e) => {
setEmployee(e.target.value);
}}
aria-label="Select Employee"
>
{employees &&
employees.map((employee) => {
return (
<option key={employee.id} value={employee.id}>
{`${employee.firstName} ${employee.surname}`}
</option>
);
})}
</Form.Select>
</Form.Group>
<Form.Group className="mb-2" controlId="addTimeFormDate">
<Form.Label className="mb-0">
<strong>Date:</strong>
</Form.Label>
<Form.Control
type="text"
onFocus={(e) => (e.target.type = "date")}
onChange={(e) => {
setDate(e.target.value);
}}
defaultValue={date}
placeholder={date}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="addTimeFormHours">
<Form.Label className="mb-0">
<strong>Hours:</strong>
</Form.Label>
<Form.Control
type="number"
defaultValue={0}
onChange={(e) => setHours(parseInt(e.target.value, 10))}
placeholder={0}
min={0}
/>
</Form.Group>
</Form>
<Button
variant="success"
onClick={() => {
handleAddWorkItem(sprint.id, date, hours);
}}
>
Add Time
</Button>
Thank you!

Populate react formik form with existing data

i am new to react, can anyone explain to me how can i manipulate or repopulate my existing form from backend data in react.
I am trying to edit and existing item in the inventory that i wanna change values for. i am using formik with react and formik grid. for data i am using AXIOS.
What i am trying to do is to get edit a specific entry from my database which has changed values. it's like trying to update values
<Formik
validationSchema={schema}
initialValues={{
name: "",
numberOfSets: "0",
sortValue: "0",
boxType: "",
price: "",
photo: "",
}}
onSubmit={({
name,
numberOfSets,
sortValue,
boxType,
price,
photo,
}) => {
boxService.addBox(
name,
numberOfSets,
sortValue,
boxType,
price,
photo
);
alert("Box added Successfully!"); // Box or Gift it's same thing
window.location.reload(false);
}}
>
{({
values,
errors,
touched,
handleBlur,
handleSubmit,
setFieldValue,
}) => {
return (
<Form
form={form}
name="edit-gift"
onFinish={handleSubmit}
{...layout}
labelAlign="left"
>
// These are the fields i am trying to manipulate
<Form.Item name="name" label="Name">
<Input
name="name"
title="Product Name"
dataIndex="name"
key="productName"
value={values.name}
onChange={(e) => setFieldValue("name", e.target.value)}
onBlur={handleBlur}
placeholder="Please enter Box Name"
/>
{errors?.name && touched?.name && (
<Text type="danger">{errors?.name}</Text>
)}
</Form.Item>
<Form.Item name="numberOfSets" label="Number of Sets">
<Input
name="numberOfSets"
type="number"
value={values.numberOfSets}
onChange={(e) =>
setFieldValue("numberOfSets", e.target.value)
}
onBlur={handleBlur}
placeholder="Please enter Number of Sets"
/>
{errors?.numberOfSets && touched?.numberOfSets && (
<Text type="danger">{errors?.numberOfSets}</Text>
)}
</Form.Item>
<Form.Item name="sortVlaue" label="Sort Value">
<Input
name="sortVlaue"
type="number"
value={values.sortValue}
onChange={(e) => setFieldValue("sortVlaue", e.target.value)}
onBlur={handleBlur}
placeholder="Please enter soring value"
/>
{errors?.numberOfBoxes && touched?.numberOfBoxes && (
<Text type="danger">{errors?.numberOfBoxes}</Text>
)}
</Form.Item>
<Form.Item name="boxType" label="Type">
<Select
value={values.boxType}
onChange={(value) => setFieldValue("boxType", value)}
onBlur={handleBlur}
placeholder="Please enter Box Type"
>
<Select.Option value="reward">Reward</Select.Option>
<Select.Option value="doublerandom">
Double Random
</Select.Option>
</Select>
{errors?.boxType && (
<Text type="danger">{errors?.boxType}</Text>
)}
</Form.Item>
<Form.Item name="price" label="Price">
<Input
name="price"
title="Product Price"
dataIndex="price"
key="price"
value={values.price}
onChange={(e) => setFieldValue("price", e.target.value)}
onBlur={handleBlur}
placeholder="Please enter Box Price"
/>
{errors?.price && touched?.price && (
<Text type="danger">{errors?.price}</Text>
)}
</Form.Item>
<Form.Item name="photo" label="Product Picture">
<div className="dropzone-container">
{values.photo && <img src={values.photo} alt=""></img>}
{!values.photo && (
<Dropzone
onDrop={(acceptedFiles) => {
acceptedFiles.map((file) => {
console.log(file);
});
let fr = new FileReader();
fr.onload = function () {
setFieldValue("photo", fr.result);
setFieldValue("imgName", acceptedFiles[0].name);
console.log(acceptedFiles[0]);
};
fr.readAsDataURL(acceptedFiles[0]);
}}
accept={{ "image/*": [] }}
maxSize={1000000}
>
{({ getRootProps, getInputProps }) => (
<section>
<div {...getRootProps({ style })}>
<input {...getInputProps()} />
<p>
Drag 'n' drop some files here, or click to
select files
</p>
<aside>
Tips: The size ratio of the photo is: 750:216,
the maximum recommended size is 1M, and the
format is: .jpg, .jpeg, .png
</aside>
</div>
</section>
)}
</Dropzone>
)}
</div>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Cofirm save
</Button>
</Form.Item>
</Form>
);
}}
</Formik>
You could either:
rerender the Formik component when your data is available and pass it to the initialValues prop by doing something like
results?.data && <Formik initialValues={{...}}>...</Formik>
or set the values manually with setValues after the data is available
const {setValues, values, ...} = useFormik({...});
useEffect(() => {
setValues(results?.data); // use any fields from your data
}, [results]} // this is the data from your api

Issue with Gatsby Netlify Form not receiving Submissions

I got the Netlify form working and accepting submissions but once I started setting up AJAX according to https://docs.netlify.com/forms/setup/, I can't figure out why submissions aren't being received.
Things I've tried:
Removing Hidden "form-name" input
Removing Recaptcha
Running "gatsby clean"
Removing opening Form tag's method attribute (method: "POST")
Removing action attribute from the opening Form tag and setting it directly in handleSubmit:
.then(() => navigate("/thank-you/"))
Any suggestions or fixes are really appreciated!
contact-form.js:
import React, { setState } from "react"
import styled from "styled-components"
import Recaptcha from "react-google-recaptcha"
import { navigate } from "gatsby"
import { Button, Col, Form, Row } from "react-bootstrap"
import { breakpoints } from "../utils/breakpoints"
const RECAPTCHA_KEY = process.env.GATSBY_RECAPTCHA_KEY
export default function ContactForm() {
const [state, setState] = React.useState({})
const recaptchaRef = React.createRef() // new Ref for reCaptcha
const [buttonDisabled, setButtonDisabled] = React.useState(true)
const handleChange = e => {
setState({ ...state, [e.target.name]: e.target.value })
}
const encode = data => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&")
}
const handleSubmit = e => {
e.preventDefault()
const form = e.target
const recaptchaValue = recaptchaRef.current.getValue()
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": "contact",
"g-recaptcha-response": recaptchaValue,
...state,
}),
})
.then(() => navigate(form.getAttribute("action")))
.catch(error => alert(error))
}
return (
<Form
name="contact"
method="POST"
netlify
action="/thank-you"
netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
onSubmit={handleSubmit}
>
<Row>
<Col md={12}>
<h3>Message Us</h3>
</Col>
</Row>
<Row>
<Col md={6}>
<Form.Group hidden>
<Form.Label htmlFor="bot-field">
Bot Field: Humans do not fill out!
</Form.Label>
<Form.Control name="bot-field" />
<Form.Control name="form-name" value="contact" />
</Form.Group>
<Form.Group>
<Form.Label htmlFor="first-name">First Name</Form.Label>
<Form.Control
required
size="lg"
type="text"
name="first-name"
onChange={handleChange}
/>
</Form.Group>
</Col>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="last-name">Last Name</Form.Label>
<Form.Control
required
size="lg"
type="text"
name="last-name"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="email">Email</Form.Label>
<Form.Control
required
size="lg"
type="email"
name="email"
onChange={handleChange}
/>
</Form.Group>
</Col>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="phone">Phone (Optional)</Form.Label>
<Form.Control
size="lg"
type="tel"
name="phone"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={12}>
<Form.Group>
<Form.Label htmlFor="message">Message</Form.Label>
<Form.Control
required
as="textarea"
rows="3"
placeholder="Enter your message here."
name="message"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={12}>
<FormControls>
<Recaptcha
ref={recaptchaRef}
sitekey={RECAPTCHA_KEY}
size="normal"
id="recaptcha-google"
onChange={() => setButtonDisabled(false)} // disable the disabled button!
className="mb-3"
/>
<div>
<Button className="mr-3" type="reset" value="Eraser">
Clear
</Button>
<Button type="submit" disabled={buttonDisabled}>
Send
</Button>
</div>
</FormControls>
</Col>
</Row>
</Form>
)
}
const FormControls = styled.div`
display: flex;
align-items: center;
flex-direction: column;
#media ${breakpoints.sm} {
flex-direction: row;
justify-content: space-between;
}
button[disabled] {
cursor: not-allowed;
}
gatsby-config:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `...`,
description: `...`,
author: `...`,
},
flags: {
DEV_SSR: false,
},
plugins: [
`gatsby-plugin-gatsby-cloud`,
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-plugin-styled-components`,
`gatsby-plugin-typography`,
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`,
},
}
HTML File in Static Folder:
<form
data-netlify="true"
name="contactVivaz"
method="POST"
data-netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
>
<input type="text" name="first-name" />
<input type="text" name="last-name" />
<input type="email" name="email" />
<input type="tel" name="phone" />
<textarea name="message"></textarea>
<div data-netlify-recaptcha="true"></div>
</form>
Your state management looks good, what it's mandatory is to have (and to check) the input value of hidden fields that must match exactly the form name in the JSX as well as in the Netlify's dashboard. Assuming that everything is well named, as it seems, I believe your issue comes from the Form component, which should looks like:
<Form
name="contact"
method="POST"
action="/thank-you"
data-netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
data-netlify="true"
onSubmit={handleSubmit}
>
Note the data-netlify-honeypot and data-netlify value.
For adding the reCAPTCHA field, you have two options:
Allowing Netlify to handle all the related logic by adding simply an empty <div> like:
<div data-netlify-recaptcha="true"/>
Adding a custom reCAPTCHA (your case) what required to add the environment variables in your Netlify dashboard (prefixed with GATSBY_) and sending the response with the g-recaptcha-response field so your POST request needs to have that field as the docs suggest:
The Netlify servers will check the submissions from that form, and
accept them only if they include a valid g-recaptcha-response value.
Further references to base your setup:
https://www.gatsbyjs.com/docs/building-a-contact-form/
https://www.seancdavis.com/blog/how-to-use-netlify-forms-with-gatsby/
https://medium.com/#szpytfire/setting-up-netlify-forms-with-gatsby-and-react-5ee4f56a79dc

How to clear input fields after submit in react

so i'm creating my portfolio and i am now on the final page, the contact page. I have it almost finished. I have it hooked up with emailjs and i receive emails with the message inputted as expected.
The problem i'm having is, when the form is submitted, i don't know how to clear the UI input fields. I could disregard using e.preventDefault(), however, i would like to keep that, as i want to style the page if the desired result has been achieved(message sent), or if an error has occurred. I would like to mention that i had used state for the name, email and message beforehand, however, i was unable to use the state variables in conjunction with the emailjs syntax, more specifically, with the "e.target" section. When the form is submitted, the result is the message being sent to my email, with the text inputted by the user still in the input fields.
The code is below, with some names left as hidden for privacy reasons:
import React, { useState } from 'react'
import { Box, Grid, Typography, Button} from '#material-ui/core'
import Navbar from './Navbar';
import Styles, { InputField } from './Styles'
import SendIcon from '#material-ui/icons/Send'
import emailjs from 'emailjs-com'
function Contact() {
const classes = Styles()
function sendEmail(e) {
e.preventDefault()
emailjs.sendForm('gmail', 'hidden', e.target, 'hidden')
.then((result) => {
console.log(result.text);
result.text ==="OK" ? console.log("it worked") : console.log("didnt work")
}, (error) => {
console.log(error.text);
});
}
return (
<Box component='div'>
<Navbar/>
<Grid container justify='center'>
<Box component='form' className={classes.contactContainer} onSubmit={sendEmail}>
<Typography variant='h5' className={classes.contactHead}>Contact Me</Typography>
<InputField
id="name"
name="name"
fullWidth={true}
label="Name"
variant="outlined"
margin='dense'
size='medium'
/>
<br/>
<InputField
id="email"
name="email"
fullWidth={true}
label="Email"
variant="outlined"
margin='dense'
size='medium'
/>
<br/>
<InputField
id="message"
name="message"
fullWidth={true}
label="Enter Message Here"
multiline
rows={8}
variant="outlined"
margin='dense'
size='medium'
/>
<br/>
<Button
type="submit"
variant='outlined'
fullWidth={true}
endIcon={<SendIcon/>}
className={classes.contactButton}>
Contact Me
</Button>
</Box>
</Grid>
</Box>
)
}
export default Contact
For the simplest way to do it in your code, use useState to declare initial value of the fields such as:
const [name, setName] = useState("");
Then you need to set the "value" param in your InputField component, eg:
<InputField
id="name"
name="name"
fullWidth={true}
label="Name"
variant="outlined"
margin='dense'
size='medium'
value={name}
/>
And after receiving the result in emailjs.sendForm, use setName to reset the value of the name field, eg:
setName("")
Use the similar method for other fields.
Thank you for the answer, it helped, however did not fully fix the problem. That being said, i was able to find a solution. I used the onChange param and passed through a function which changes the state AND the value. Also, after receiving the result in emailjs.sendForm, i reset the value of all the fields.
const handleChange = (event) => {
event.target.name=="name"
? setName(event.target.value)
: event.target.name=="email"
? setEmail(event.target.value)
: event.target.name=="message"
? setMessage(event.target.value)
: console.log("error")
};
function sendEmail(e) {
e.preventDefault()
emailjs.sendForm('gmail', 'hiddenForPrivacy', e.target, 'hiddenForPrivacy')
.then((result) => {
console.log(result.text);
result.text ==="OK" ? console.log("it worked") : alert("didnt work")
setName("")
setMessage("")
setEmail("")
}, (error) => {
console.log(error.text);
});
}
The input fields now look like this:
return (
<Box component='div'>
<Navbar/>
<Grid container justify='center'>
<Box component='form' className={classes.contactContainer} onSubmit={sendEmail}>
<Typography variant='h5' className={classes.contactHead}>Contact Me</Typography>
<InputField
id="name"
name="name"
fullWidth={true}
label="Name"
variant="outlined"
margin='dense'
size='medium'
onChange={(e) => handleChange(e)}
value={name}
/>
<br/>
<InputField
id="email"
name="email"
fullWidth={true}
label="Email"
variant="outlined"
margin='dense'
size='medium'
onChange={(e) => handleChange(e)}
value={email}
/>
<br/>
<InputField
id="message"
name="message"
fullWidth={true}
label="Enter Message Here"
multiline
rows={8}
variant="outlined"
margin='dense'
size='medium'
onChange={(e) => handleChange(e)}
value={message}
/>
<br/>
<Button
type="submit"
variant='outlined'
fullWidth={true}
endIcon={<SendIcon/>}
className={classes.contactButton}>
Contact Me
</Button>
</Box>
</Grid>
</Box>

Npm reactjs -input -validators

index.js:1446 Warning: React does not recognize the validatorErrMsg prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase validatorerrmsg instead. If you accidentally passed it from a parent component, remove it from the DOM element.
in input (created by t)
in div (created by t)
in t (created by t)
in div (created by t)
in t (created by t)
in div (created by t).
This is the Error which stuck my brain since two days..
The required js file include following code .
class SharedComponent extends Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
data: {},
};
}
handleChange(event, inputValue, inputName, validationState, isRequired) {
const value = (event && event.target.value) || inputValue;
const { data } = this.state;
data[inputName] = { value, validation: validationState, isRequired };
this.setState({
data,
});
const formData = formInputData(this.state.data);
const isFormValid = formValidation(this.state.data);
console.log('shared component',formData+isFormValid);
}
handleSubmit(event) {
event.preventDefault();
const isFormValid = formValidation(this.state.data);
if (isFormValid) {
// do anything including ajax calls
this.setState({ callAPI: true });
} else {
this.setState({ callAPI: true, shouldValidateInputs: !isFormValid });
}
}
render() {
const passwordValue = this.state.data.password && this.state.data.password.value;
return (
<form className="example">
<Row>
<Col md={6}>
<Field required
label="Full Name" name="fullName" placeholder="First Last"
onChange={this.handleChange}
value={this.state.data.fullName}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
<Col md={6}>
<Field
validator="isEmail" required
label="Email" name="email" placeholder="Email"
onChange={this.handleChange}
value={this.state.data.email}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
</Row>
<Row>
<Col md={6}>
<Field
validator="isAlphanumeric" required minLength={8}
minLengthErrMsg="Short passwords are easy to guess. Try one with atleast 8 characters"
label="Create a password" name="password" type="password" placeholder="Password"
onChange={this.handleChange}
value={this.state.data.password}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
<Col md={6}>
<Field
validator="equals" required comparison={passwordValue}
validatorErrMsg="These passwords don't match. Try again?"
label="Confirm password" name="confirmPassword" type="password" placeholder="Password"
onChange={this.handleChange}
value={this.state.data.confirmPassword}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
</Row>
<Field
required
requiredErrMsg="Enter your address so we can send you awesome stuff"
label="Address" name="address" placeholder="1234 Main St"
onChange={this.handleChange}
value={this.state.data.address}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
<Field
label="Address 2"
name="address2" placeholder="Apartment, studio, or floor"
onChange={this.handleChange}
value={this.state.data.address2}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
<Row>
<Col md={6}>
<Field
maxLength={20} required label="City"
name="inputCity"
onChange={this.handleChange}
value={this.state.data.inputCity}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
<Col md={3}>
<label htmlFor="inputState">State</label>
<select
name="inputState" className="form-control"
onChange={this.handleChange}
value={this.state.data.inputState ? this.state.data.inputState.value : ''}
>
<option>Choose...</option>
<option value="ALABAMA">ALABAMA</option>
<option value="ALASKA">ALASKA</option>
<option value="ARIZONA">ARIZONA</option>
<option>...</option>
</select>
</Col>
<Col md={3}>
<Field
validator="isPostalCode" locale="US" required maxLength={10}
validatorErrMsg="Enter a valid US Zip"
label="Zip" name="inputZip"
onChange={this.handleChange}
value={this.state.data.inputZip}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
</Row>
<button
type="submit" onClick={this.handleSubmit} className="btn btn-danger"
>Sign up
</button>
{this.state.callAPI
?
<pre className="resultBlock">
{JSON.stringify(formInputData(this.state.data), null, 4)}
</pre>
: null
}
</form>
);
}
}
This is my js file for rect js form with validation .
Can Anyone help to walk through it ..THANKS.
The message you're seeing means that the Field component isn't itself doing anything with the validatorErrMsg prop; instead, it's simply passing it down to the DOM node (probably an input element). That property has no special meaning to input elements, so it has no effect.
You need to check the documentation for whatever library you're getting Field from. That should specify what props you can use.
Alternatively, if you created the Field component yourself, you need to implement the logic for handling the validatorErrMsg prop yourself, within that component.

Resources