I'm using formik.resetForm() to remove values from text fields in a form after submitting the data.
...
const handleSubmitProduct = async (values: Object, resetForm: any) => {
... code to handle my form data ...
resetForm()
if (response.ok) {
console.debug(response.status)
} else {
console.error(response)
}
}
const validate = (values: Object) => {
const errors: any = {}
if (!values.product_name) {
errors.product_name = "Include name"
}
return errors
}
... initialValues defined ...
const formik = useFormik({
initialValues: initialValues,
validate,
onSubmit: (values: Object, { resetForm }) => {
console.debug(JSON.stringify(values, null, 2))
handleSubmitProduct(values, resetForm)
},
})
return (
<FormLabel>Display name</FormLabel>
<TextField
onChange={formik.handleChange}
id="product_name"
onBlur={formik.handleBlur}
error={formik.touched.product_name && Boolean(formik.errors.product_name)}
helperText={formik.touched.product_name && formik.errors.product_name}
/>
<Button onClick={() => formik.handleSubmit()} variant="contained">
Submit
</Button>
)
I know there are many other questions like this but mine is different where I know the underlying Formik resources for values, errors, touched have been cleared but the values are still present in the text boxes.
The issue is I know the underlying Formik objects are cleared because after I submit, the validation triggers and prompts me like there is no value in the text field.
I've tried
resetForm({values: {initialValues}}) has the same result
resetForm(initialValues) has the same result
Use action.resetForm({values: {initialValues}}) in the onSubmit() which same result
https://codesandbox.io/s/mui-formik-fr93hm?file=/src/MyComponent.js but this approach uses the <Formik /> as opposed to useFormik which would change up my entire page but I'm in process to try anyway
I think the problem is that value of TextField is not value of formik. so the TextField is not controlled and by chaning value of formik it won't change.
assigning value of formik to it will do what you want
value={formik.values.firstName}
like this :
<TextField
onChange={formik.handleChange}
id="product_name"
value={formik.values.firstName}
onBlur={formik.handleBlur}
error={formik.touched.product_name && Boolean(formik.errors.product_name)}
helperText={formik.touched.product_name && formik.errors.product_name}
/>
I'm creating a form with a file upload with help of react-hook-form and Yup. I am trying to use the register method in my child component. When passing register as a prop (destructured in curly braces) the validation and submiting doesn't work. You can always submit the form and the submitted file object is empty.
Here's a sandbox link.
There are several of problems with your code.
1- register method returns an object with these properties:
{
onChange: function(){},
onBlur:function{},
ref: function(){}
}
when you define your input like this:
<input
{...register('photo')}
...
onChange={(event) => /*something*/}
/>
actually you are overrding the onChange method which has returned from register method and react-hook-form couldn't recognize the field change event. The solution to have your own onChange alongside with react-hook-form's onChange could be something like this:
const MyComp = ()=> {
const {onChange, ...registerParams} = register('photo');
...
return (
...
<input
{...params}
...
onChange={(event) => {
// do whatever you want
onChange(event)
}}
/>
);
}
2- When you delete the photo, you are just updating your local state, and you don't update photo field, so react-hook-form doesn't realize any change in your local state.
the problems in your ImageOne component could be solved by change it like this:
function ImageOne({ register, errors }) {
const [selectedImage, setSelectedImage] = useState(null);
const { onChange, ...params } = register("photo");
return (
...
<Button
className="delete"
onClick={() => {
setSelectedImage(null);
//Make react-hook-form aware of changing photo state
onChange({ target: { name: "photo", value: [] } });
}}
>
...
<input
//name="photo"
{...params}
type="file"
accept="image/*"
id="single"
onChange={(event) => {
setSelectedImage(event.target.files[0]);
onChange(event); // calling onChange returned from register
}}
/>
...
);
}
3- Since your input type is file so, the value of your photo field has length property that you can use it to handle your validation like this:
const schema = yup.object().shape({
photo: yup
.mixed()
.test("required", "photo is required", value => value.length > 0)
.test("fileSize", "File Size is too large", (value) => {
return value.length && value[0].size <= 5242880;
})
.test("fileType", "Unsupported File Format", (value) =>{
return value.length && ["image/jpeg", "image/png", "image/jpg"].includes(value[0].type)
}
)
});
Here is the full edited version of your file.
to validate an input filed in react-hook-form I am doing something like this
<input type="text" id="name" ref={register({ required: true, maxLength: 30 })} />
but thats at the submit time .. after I get response from the remote api endpoint I need to show some validation message .. in the same input field ...
You can use trigger function to trigger validation programmatically:
const { trigger } = useForm();
const triggerValidation = () => {
trigger() // all fields
trigger("lastName") // specific field
}
Documentation: https://react-hook-form.com/api/#trigger
I made some form validation in react, Can i use a few global variables from my state in one function for my form validation? Whats the way to keep it simple and still give a different conditions to every input? something wrong and I'd like to some help, I would like to not include the regexp pattern for the email or anything..
Thanks Everyone!
Registration.js
import React, { Component } from 'react'
export default class Registration extends Component {
state={
userName:'',
password:'',
email:'',
age:'',
backgroundColorInput:'white'
}
validLoginDetails=(item)=> {
locationOfS = email.indexOf('#');
this.setState({userName:item.target.value});
if(item.target.value.length>5 && item.target.value.length<9){
this.setState({backgroundColorInput:'green'})
}
this.setState({password:item.target.value});
if(item.target.value.length<7){
this.setState({backgroundColorInput:'red'})
}
this.setState({email:item.target.value});
if (item.target.value.locationOfS.indexOf(4) != -1) {
this.setState({backgroundColorInput:'green'} )
}
else{
this.setState({backgroundColorInput:'red'})
}
}
render() {
return (
<div>
<input placeholder='Enter your name' onChange={this.validLoginDetails} style={{backgroundColor: this.state.backgroundColorInput}} /><br/>
<input type='password' placeholder='Enter your a password' onChange={this.validLoginDetails} style={{backgroundColor: this.state.backgroundColorInput}} /><br/>
<input placeholder='Enter your Age' onChange={this.validLoginDetails} style={{backgroundColor: this.state.backgroundColorInput}} /><br/>
<input type="email" placeholder='Enter your Email' onChange={this.validLoginDetails} style={{backgroundColor: this.state.backgroundColorInput}} /><br/>
<button onClick={this.func}>submit</button>
</div>
)
}
}
App.js
import React from 'react';
import './App.css';
import Registration from './components/Registration.js';
import Main from './components/Main.js';
function App() {
return (
<div className="App">
<Registration/>
<Main/>
</div>
);
}
export default App;
Here are some of my recent problems and solutions that I hope will help you.
Recently I want to create a signup page with react. I need a library help me manage the form state and validate the form values. Then I choose the famous 'formik' + 'Yup'. But after some try, I found that it was not up to the job.
formik validate every fields when any fields value change or blur. For simple validation, it is not a big problem. But I need to check the usability of user name and email through network which may cost many time. And when checking, A spin is presented to the user. So the validation can't be triggered by change event. On the other hand, if the user name has been checked and not change, it should not be checked again. Becuase the user will not want to see a spin when he doesn't change the user name field. For almost all the form library, validation will be triggered before submit. but for those fields which has been validated and not changed yet, the validation should not be triggered. Formik is difficult to achieve the above requirements
At last I developed my own library. It support validate each field with separate triggers.
by and large there are three trigger: change, blur and submit.
For change, when the field value changed, the validation happen.
For blur, the situation will be a bit complicated. When the blur happen, if the field already has an error and the field has not changed from last validation, it should not be validated again. If the field has not an error, and the field value has not changed from last validation, it should not be validated again. If the field has not an error, but the field has been changed from last validation, it should be validated now.
For submit, similar to the 'blur' event, when submit happen, if the field already has an error and the field value has not been changed from last validation, no need to validate again, and terminate submission. If the field has not error and the field value has not been changed from the last validation, the field is considered to have been validated and does not need to be re-validated. If the field has not error and the field value has been changed from the last validation, a validation task should be started again.
There is a working demo
This is the code example
import React from 'react';
import { createValidator, useForm, OnSubmitFunction, REG_SPECIAL, string, sameWithWhenExists } from 'powerful-form-hook';
export const Demo = () => {
const initialValues = React.useMemo(() => ({
userName: '',
email: '',
password: '',
conformedPassword: '',
age: '',
}), []);
const validate = React.useMemo(() => createValidator<typeof initialValues>({
userName: (value) => {
if (!value) throw 'User name is required.'
if (value.length > 5 && value.length < 9) throw 'The length of user name should longer than 5 and shortter than 9.'
},
password: [
string()
.required('Password is required.')
.composedOf('Password must be composed of upper and lower case letters, Numbers and special keyboard symbols', /[a-z]+/i, /\d+/, REG_SPECIAL)
.matchSomeOf('The password must contain uppercase letters or special keyboard symbols', /[A-Z]+/, REG_SPECIAL)
.min(6, 'Password length must be greater than or equal to 6')
.max(24, 'Password length must be less than or equal to 24'),
// the validate task will trigger by blur of itself and conformedPassword field.
{
triggers: {
trigger: 'blur',
fields: ['conformedPassword'],
},
validate: sameWithWhenExists('conformedPassword', 'Enter the same password twice'),
},
],
conformedPassword: [
string('Password should be a string.'),
// the validate task will trigger by blur of itself and password field.
{
triggers: {
trigger: 'blur',
fields: ['password'],
},
validate: sameWithWhenExists('password', 'Enter the same password twice'),
},
],
age: string().matchSomeOf(/\d+/)
// same as userName.
email: [
string().required('Email is required.').trimmed('Email can not start or end with space.'),
],
}), []);
// Only when validate successful, the form submit. And if some validate task is running in the background or the form is submitting, the form will not be sumbited.
const onSubmit: OnSubmitFunction<typeof initialValues> = React.useCallback(async (values: typeof initialValues) => {
alert('submit successful');
}, []);
// handleChanges accept both event and value. For default, handleChanges will extract the value from event.target.value. For component like CheckBox which accept checked, use handleChanges[field].checked.
const { errors, values, handleChanges, handleBlurs, handleSubmit, submitting, validating } = useForm({
initialValues,
validate,
onSubmit,
});
return (
<form onSubmit={handleSubmit} noValidate>
<div>
<input placeholder='Enter your name' onChange={handleChanges.userName} onBlur={handleBlurs.userName} />
{ errors.userName.error ? errors.userName.message : null }
</div>
<div>
<input type='password' placeholder='Enter your a password' onChange={handleChanges.password} onBlur={handleBlurs.password} />
{ errors.password.error ? errors.password.message : null }
</div>
<div>
<input type='password' placeholder='Conform your a password' onChange={handleChanges.conformedPassword} onBlur={handleBlurs.conformedPassword} />
{ errors.conformedPassword.error ? errors.conformedPassword.message : null }
</div>
<div>
<input placeholder='Enter your Age' onChange={handleChanges.age} onBlur={handleBlurs.age} />
{ errors.age.error ? errors.age.message : null }
</div>
<div>
<input type="email" placeholder='Enter your Email' onChange={handleChanges.email} onBlur={handleBlurs.email} />
{ errors.email.error ? errors.email.message : null }
</div>
<button type="submit">submit</button>
{ submitting ? 'Submitting...' : validating ? 'Validating...' : null }
</form>
)
}
I am using Material-UI in react application. What I am trying to do is to change the label "Please fill out this field" of text-field when we set the required attribute.
I tried to use setCustomValidity with inputProps, but nothing happens.
There are two types of this label. One is a tooltip that showed up when the mouse is hovered on the text-field, the other when we submit the form.
The error message you are getting is not material-ui, but is the browser handling the error. This cannot be changed since the browser renders this based on the "required" attribute. You can only change this by doing custom error handling on your form.
Here is the code snippet which i used in my personal project:
<TextField
error={this.props.error_val
? true
: false
}
required={this.props.isRequired ? true : false}
type={this.props.type}
label={this.props.label}
variant={this.props.VARIANT}
className={classes.root}
/>
You can use required and error attribute combination for deciding whether the input is filled or not.
Secondly, you can write a validate() which is basically a switch statement where you will pass "label name", "value" and put the return value into your <TextField/> component.
Snippet:
validate = (name, value) => {
let error = "";
switch (name) {
case "name":
error = (!value || value.length == 0) && "Please enter the name";
break;
}
return error;
}
You can replace the 'required' validation message for the TextField component with a custom-validation message (when submitting the form) as follows:
<TextField
onInvalid={() => {
document
.getElementById("business-email-textfield")
.setCustomValidity("Please type a valid email address");
}}
required
id="business-email-textfield"
label="Business Email"
name="email"
onChange={handleInput}
variant="standard"
/>
In the handleInput function you should handle the input of course, but you should also reset the custom-validation message. For example:
const [formInput, setFormInput] = useReducer(
(state, newState) => ({ ...state, ...newState }),
{
email: "",
businessType: "",
}
);
const handleInput = (evt) => {
const name = evt.target.name;
const newValue = evt.target.value;
setFormInput({ [name]: newValue });
//the line below clears the custom-validatio message
document.getElementById(evt.target.id).setCustomValidity("");
};