React: Yup conditional validation only when a field is visible - reactjs

I'm trying to implement form validation using formik & yup in React. I have a login/register form with three fields (name,email,password). Name field is conditionally rendered when 'create an account' button is clicked. I want the name field to be required only when form is in register state. I'm using a state variable isLogin to save the form's current state, also using it to initialise showName boolean in formik's initialValues. Right now, name field has no validation applied on it and form can be submitted if name field is empty.
My Code
const [isLogin, setIsLogin] = useState(true);
const initialAuthFormValues = {
hideName: isLogin,
name: "",
email: "",
password: "",
};
My Validation Schema
const authFormValidationSchema = Yup.object().shape({
hideName: Yup.boolean(),
name: Yup.string().when("hideName",{
is: false,
then: Yup.string().required("Name is required"),
}),
email: Yup.string().required("Email is required"),
password: Yup.string().required("Password is required"),
});
My Component looks like this
<Formik
initialValues={initialAuthFormValues}
validationSchema={authFormValidationSchema}
onSubmit={submitHandler}
>
{(formik) => (
<Form>
{!isLogin && (
<TextField
label="Name"
type="text"
name="name"
placeholder="Name"
/>
)}
<TextField
label="Email"
type="text"
name="email"
placeholder="Email"
/>
<TextField
label="Password"
type="password"
name="password"
placeholder="Password"
/>
<div className={classes.actions}>
<Button type="submit"> {isLogin ? "Login" : "Create Account"} </Button>
<Button
type="reset"
className="toggle"
onClick={() => { setIsLogin((prevState) => !prevState); }}
>
{isLogin ? "Create new account" : "Login with existing account"}
</Button>
</div>
</Form>
</section>
)}
</Formik>

You can use authFormValidationSchema as a state , and update this state in case that button clicked :
const authFormValidationSchema = {
email: Yup.string().required("Email is required"),
password: Yup.string().required("Password is required"),
};
const [authFormValidationSchema, setAuthFormValidationSchema] = useState(Yup.object());
track the status when button is clicked in a useEffect, and update state of authFormValues accordingly :
useEffect(()=>{
let authFormValidationSchema_ = JSON.parse(JSON.stringify(authFormValidationSchema))
if(!buttonIsClicked)
setAuthFormValidationSchema(Yup.object(authFormValidationSchema_));
else setAuthFormValidationSchema(Yup.object({...authFormValidationSchema_, name: Yup.string().required("Name is required") }));
},[buttonIsClicked]);

Finally found the solution to the problem : In my code, action is my prop
First, create a variable in your JS that will hold the logic:
let passwordTest
if (action === "Register") {
passwordTest = {
password2: Yup
.string().trim()
.required("Please confirm your password")
.oneOf([Yup.ref('password'), null], 'Passwords must match')
} else {
passwordTest = null
}
Basically above you are saying that if the props is Register (if this
form is rendered for registering purpose and not login), then create
the field apply the validation listed, otherwise, this field will be
null.
Then, in your Yup schema destructure your variable :
const validationSchemaYup = Yup.object().shape({
other fields validation logic...
...passwordTest,
other fields validation logic...
Here you add your new custom validation logic, don't forget to destructure!

Related

Make yup validate differently depending on what function I call

https://codesandbox.io/s/nice-cohen-k3kdtq?file=/src/App.js Here is the codesandbox example of my code
What I need to do is when I click the 'Preview' button I want to disable validation on last two fields (price, category) and when I click 'Submit' I want to validate all the fields. I tried to change react-hook-form resolver depending on state but it doesn't let me and had an idea about making fields not required when boolean variable from component changes but I don't know how can I send this variable to yup schema
const nftSchema = yup.object().shape({
NFTCollectionAddress: yup
.string()
.required("Collection address is required")
.test("len", "Not a valid address", (val) => val.length === 42)
.matches("0x", "Not a valid address"),
NFTTokenID: yup
.number()
.typeError("You must specify a number")
.required("Token ID is required"),
price: yup
.string()
.required("Price is required")
.test("inputEntry", "The field should have digits only", digitsOnly)
.test(
"maxDigitsAfterDecimal",
"Number cannot have more than 18 digits after decimal",
(number) => /^\d+(\.\d{1,18})?$/.test(number)
),
category: yup.string().required("Category is required")
});
export default function App() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm({
resolver: yupResolver(nftSchema),
});
const onSubmit = (data) => {
};
const handlePreview = (data) => {
};
return (
<form>
<h4>Token ID</h4>
<input
name="NFTTokenID"
type="text"
{...register("NFTTokenID")}
/>
<h4>Collection</h4>
<input
name="NFTCollectionAddress"
type="text"
{...register("NFTCollectionAddress")}
/>
<h4>Price</h4>
<input
name="price"
type="text"
{...register("price")}
/>
<h4>Category</h4>
<input
name="category"
type="text"
{...register("category")}
/>
<button onClick={handleSubmit(onSubmit)}>Submit</button>
<button onClick={handleSubmit(handlePreview)}>Preview</button>
</form>
</div>
);
}
What about creating a different schema for preview, and changing the schema passed to yupResolver based on isPreview? On Preview button also would just set the isPreview state, not use the handleSubmit function.

Yup: how to compare one field with other? Ref neither parent.field not working

This is the yup schema:
let schema = yup.object().shape({
password: yup.string().required('Enter password'),
confirm: yup.string().required('Re-enter password')
.test('passwords-match', 'Password and confirmation do not match', function(value){
const t = yup.ref('password'); // some bulky object
const t1 = t.getValue(); // undefined too
const t2 = this.parent.password; // undefined too
const a = this.resolve(t) // undefined even after entering value
return a === value
})
For some reason, comparison with another field is not working.
What am I missing?
Some idea just came to me. Maybe something is wrong with this validator I'm using from here: https://stackblitz.com/edit/react-97lr5s?file=index.js
The full code from there:
import * as yup from 'yup';
let schema = yup.object().shape({
name: yup.string().required(),
age: yup
.number()
.required()
.typeError('Number only.')
.positive()
.integer()
.round(),
a: yup
.number()
.required()
.typeError('Number only.')
.positive()
.integer()
.round().test('', 'asdf', function(v){
console.log(this.parent.name) // undefined
return v == this.parent.age}), // okay?
});
const yupSync = {
async validator({ field }, value) {
await schema.validateSyncAt(field, { [field]: value });
},
};
const DynamicRule = () => {
const [form] = Form.useForm();
return (
<Form form={form} name="form1">
<Form.Item name="name" label="Name" rules={[yupSync]}>
<Input placeholder="Please input your name" />
</Form.Item>
<Form.Item name="age" label="Age" rules={[yupSync]}>
<Input placeholder="Please input age" />
</Form.Item>
<Form.Item name="a" label="Age" rules={[yupSync]}>
<Input placeholder="Please input a" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
Here is how you can compare two fields in Yup. You're almost there but just need some additional info in order to compare two fields.
Working example:
Yup.object().shape({
password: Yup.string().min(8).required("Password is required"),
confirmPassword: Yup.string()
.when("password", { // this should match with input field name
is: (val) => (val && val.length > 0 ? true : false),
then: Yup.string().oneOf(
[Yup.ref("password")],
"Both Password need to be same"
),
})
.required("Confirm Password is required"),
}),

Update specific value in Initial Values Formik

I am using Formik and Yup validation for my form which has firstname ,lastname & username. Username should be without spaces so I am using a onChange event and value. Yup validation is working for firstname and Lastname but not for username. When logging my values found out that username is not getting updated. I am a newbie please help me out. Thanks in advance.
const CustomTextInput =({label, ...props}) =>{
const [field, meta] = useField(props);
return(
<>
<label className="required" htmlFor={props.id || props.name}>{label}</label>
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
):null}
<input className="text-input" {...field} {...props}/>
</>
)
}
function App(){
const [regnum, Setreg]= useState("");
function avoid(e){
Setreg(e.target.value.replace(/\s+/g,''));
}
return(
<Styles>
<Formik
initialValues={{
firstname:'',
lastname: '',
username:'',
phone1:'',
email:''
}}
validationSchema={
Yup.object({
firstname: Yup.string()
.required('Required'),
lastname: Yup.string()
.required('Required'),
username: Yup.string()
.min(4,"Username should be greater than 4 characters")
.max(15,"Wooah! Username cannot be that big")
.required('Required'),
})
}
onSubmit= {(values, { setSubmitting , resetForm }) => {
setTimeout(()=> {
//My api call here
resetForm()
setSubmitting(false);
},2000)
}
}>
{props => (
<Form>
<CustomTextInput label="First Name" name="firstname" type="text" placeholder="first Name"/>
<CustomTextInput label="Last Name" name="lastname" type="text" placeholder="Last Name"/>
<CustomTextInput label="UserName" name="username" type="text" value={regnum} onChange={(event)=>avoid(event)} placeholder="Spaces will be removed"/>
<div>
<button type="submit" >{props.isSubmitting ? "Loading..." : "Submit"}</button>
</div>
</Form>
</Formik>
</Styles>
);
}
export default App;
The question is, do you want to prevent the user from using a username with spaces? If so, the easiest way is to do it through yup.
validationSchema={
Yup.object({
firstname: Yup.string()
.required('Required'),
lastname: Yup.string()
.required('Required'),
username: Yup.string()
.required('Required').matches("/\s/", "Cannot contain spaces"),
})
}
Otherwise, if you allow the user to write the username with spaces, but you want it for whichever reasons without spaces, you have to manipulate the data in the submitHandler.
By giving it a custom onChange handler to username, you overrode formik since formik uses it's onChange under the hood. Manipulate the data in the submitHandler, prior to submitting, let formik do it's thing.

Formik onSubmit function is not working on my code

I am creating a form by using react and formik.Below is my code:
<div>
<Formik
initialValues={{
email: ""
}}
onSubmit={(values: FState, setSubmitting: any) => {
console.log("Enter in submit function", values);
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 500);
}}
validationSchema={validationSchemaGlobal}
>
{({
errors,
touched,
handleBlur,
handleChange,
isSubmitting,
values,
handleSubmit
}: any) => (
<div>
<Cards>
<form onSubmit={handleSubmit}>
<CardBody>
<h4>
Enter Your Email Address and we'll send you a link to reset your
password
</h4>
<Field
type="text"
id="email"
value={values.email}
component={CustomInput}
onChange={handleChange}
onBlur={handleBlur}
/>
{errors.email && touched.email ? (
<div style={{ color: "red" }}>{errors.email}</div>
) : null}
</CardBody>
<CardFooter>
<br />
<button type="submit" disabled={isSubmitting}>
Send Password Reset Link
{/* {isSubmitting && <i className="fa fa-sponner fa-spin"/>} */}
</button>
</CardFooter>
</form>
</Cards>
</div>
)}
</Formik>
</div>
In this formik form, onSubmit function not working. I dont know why? Please tell me guys what is problem with my code?
Check your validationSchema. I ran into this problem and found that my validator was returning something that signaled to Formik the form was invalid, but no other warnings or messages were coming up. It just wouldn't submit.
Replace that prop with validator={() => ({})} i.e. just an empty object being returned. That should pass validation and trigger your onSubmit. You can restore your functionality from there.
<Formik
initialValues={{
email: ""
}}
onSubmit={() => { console.log("submit!"); }}
validator={() => ({})}
>
{/* */}
</Formik>
In my case I use Yup as validator and I accidentally had firstName and lastName in my validationSchema as required but I did not have those values in my form.
My validationSchema was,
const SignupSchema = Yup.object().shape({
firstName: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Required'),
lastName: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Required'),
email: Yup.string()
.email('Invalid email')
.required('Required'),
password: Yup.string()
.min(6, 'Password must be at least 6 characters')
.max(24, 'Password can be maximum 24 characters')
.required('Required')
})
I just deleted firstName and lastName,
const SignupSchema = Yup.object().shape({
email: Yup.string()
.email('Invalid email')
.required('Required'),
password: Yup.string()
.min(6, 'Password must be at least 6 characters')
.max(24, 'Password can be maximum 24 characters')
.required('Required')
})
So check your validationSchema and see if you require something that does not exist in your form.
I imported Form from react-bootstrap instead of formik, so I was having this issue. The issue was solved by importing the Form of formik. Sometimes, directly using Form.Control of react-bootstrap instead of Field of formik also gives this issue.
If you really have to use Form.Control you can use render prop.
A little bit late for the original question but I experienced the same issue and solved it easy but hard to find.
When I passed the "name" prop to the component I had written "DateOfBirth" instead of with lowercase, which means it didn't match my validationSchema.
My schema looks like this:
export const userSchema = yup.object().shape({
firstName: yup.string().min(1).max(50).required('Field is required'),
lastName: yup.string().min(1).max(50).required('Field is required'),
dateOfBirth: yup.date().required('Invalid input'),});
This menas the name of the component has to match
Before (Didn't work):
<DateTimePicker name="DateOfBirth" label="Date of birth" />
After (Worked):
<DateTimePicker name="dateOfBirth" label="Date of birth" />
In my case, onSubmit was not working because I forgot to wrap my form in the <form></form> tag. A stupid issue, but it can be the reason for this behavior. If the above solutions don't work, check that you have the form tag.
In my case, mistakenly I have passed validationSchema to wrong prop.
Error:
<Formik
initialValues={initialValues}
validate={validationSchema} <----- Error
>
Proper way:
<Formik
initialValues={initialValues}
validationSchema={validationSchema} <----- Good
>
This may happen because the form is being submitted but it is invalid , this may happen because the validation schema is not matching ur form for more than one reason ,
in my case , it was because there was a string , and it is been sent as null , so I just added .nullable() to the validation schema for that field.
Had extra field in my validationSchema which was declared with Yup. however that field wasn't declared in Formik hence it didn't work. After removing the field from validationSchema, it works.
I am mentioning one more possibility through which i handled.
change the button type and add onClick like this
<Button type="button" onClick={submitForm}>
also add submitForm prop at top along with values, touched etc
{({ submitForm, errors, handleChange, handleSubmit, touched, values }) => (
now its working
My mistake was I was not initializing error with blank on validation
const errors:any={};
Here is full code for login form, check the validate function
<Formik
initialValues={{ email: "", password: "" }}
validate={(formValues) => {
const errors:any={};
if (!formValues.email) {
errors.email = "Invalid email";
}
if (!formValues.password) {
errors.password = "Password is required";
}
return errors;
}}
onSubmit={async (values) => {
console.log("submit", values);
dispatch(login({ username: values.email, password: values.password }));
if (loginState.isError) {
alert(loginState.message);
}
}}
>{({ values, handleChange, errors, dirty, isValid, isSubmitting, handleSubmit, setFieldValue, setFieldTouched, setFieldError }) => (
<Form onSubmit={handleSubmit}>
<FormGroup>
<Label>Email</Label>
<Input type="email" name="email" valid={!isEmpty(errors.email)} value={values.email} onChange={handleChange}></Input>
<FormFeedback className="font-weight-bold" type="invalid" role="alert"> {errors.email}</FormFeedback>
</FormGroup>
<FormGroup>
<Label>Password</Label>
<Input type="password" name="password" value={values.password} valid={!isEmpty(errors.password)} onChange={handleChange}></Input>
<FormFeedback className="font-weight-bold" type="invalid" role="alert"> {errors.password}</FormFeedback>
</FormGroup>
<FormGroup className="text-center">
<p> {isValid === true ? "is valid" : "not valid"} </p>
<Button type="submit" color="primary" className="mt-3">Login</Button>
</FormGroup>
</Form>
)}
</Formik>
I solved this because I declared the onsubmit function without the const word (I know it's stupid)
I was having the same issue. My onSubmit function was not executing onClick on submit button.
The problem was in Yup.validation schema. There was an extra field that I did not use. I remove that field and boom.
Posting this as I had the same pronlem and the problem was even different:
My validation function was returning an errors object that always contained all fields, all with empty strings when they were correct.
Form submission seems disabled when the errors object is not empty.
In my case, the issue was Button component was outside the Formik component
<Formik initialValues={} validate={validate} onSubmit={handleSubmit}>
<Form>
</Form>
</Formik>
<Button type="submit">Submit</Button>
Moving the Button inside Form solved my issue
<Formik initialValues={} validate={validate} onSubmit={handleSubmit}>
<Form>
<Button type="submit">Submit</Button>
</Form>
</Formik>
Use instead of button tag as i worked for me.

How to set and get a datepicker value using antd with formik?

Here i am creating Datepicker with antd and passing this antd datepicker to formik field.My sample code for Datepicker with antd
import React from "react";
import { Form, DatePicker } from "antd"
import { Field } from "formik";
import moment from 'moment';
const FormItem = Form.Item;
function onChange(date, dateString) {
console.log(date, dateString);
}
const dateFormat = "MM-DD-YYYY"
// Here i am adding antd error message through DateInput
const DateInput = ({
field,
form: { touched, errors },
...props
}) => {
const errorMsg = touched[field.name] && errors[field.name]
const validateStatus = errorMsg ? "error"
: (touched[field.name] && !errors[field.name]) ? "success"
: undefined
return (
<div>
<FormItem
label={props.label}
help={errorMsg}
validateStatus={validateStatus}
hasFeedback
{...props.formitemlayout}>
<DatePicker onChange={onChange} defaultPickerValue={moment()}/>
</FormItem>
</div>
)
}
export default DateInput
i am adding this ant component to formik field component,submit the form using handleSubmit and applying the YUP validations. iam getting a problem was submitting the form iam getting the required validation of DatePicker, and problem is selecting the values of DatePicker iam not getting the value and validation message is displayed after submitting the form.
class FormikApollo extends React.Component {
render() {
const { values, handleSubmit, setFieldValue } = this.props
return (
<div align="center">
<Form onSubmit={handleSubmit}>
<Field
name="username"
label="Name"
placeholder="Enter a Name"
component={TextField}
value={values.username}
formitemlayout={formItemLayout}
/>
<Field
name="email"
label="Email"
placeholder="Enter an Email"
component={TextField}
value={values.email}
formitemlayout={formItemLayout}
/>
<Field
name="password"
label="Password"
type="password"
placeholder="Enter a Password"
component={TextField}
formitemlayout={formItemLayout}
/>
<Field
name="dateofbirth"
label="dateOfBirth"
type="date"
component={DateInput}
formitemlayout={formItemLayout}
defaultValue={values.dateofbirth}
format={dateFormat}
/>
<Button type="primary" htmlType="submit">Submit</Button>
</Form>
)
}
}
Here i am getting the values through withFormik and submitting the form using handleSubmit. Why iam not getting datepicker value and why validation message is displayed after selecting a datepicker value?
const FormikApp = (withFormik)({
mapPropsToValues({ username, email, password, dateofbirth }) {
return {
username: username || '',
email: email || '',
password: password || '',
dateofbirth: dateofbirth || ''
}
},
validationSchema: Yup.object().shape({
username: Yup.string()
.min(3, "Username must be above 3 characters")
.required("Username is required"),
email: Yup.string()
.email("Invalid Email !!")
.required("Email is required"),
password: Yup.string()
.min(6, "Password must be above 6 characters")
.required("Password is required"),
dateofbirth: Yup.string().required("Date is required")
}),
handleSubmit(values, { resetForm }) {
resetForm();
console.log(values)
}
})(FormikApollo)
In your DateInput component try to set value with setFieldValue() method of Formik whether it is valid or not. I believe you can extract it from via: form: { touched, errors, setFieldValue }.
Also check touched items in your form, and make sure that you are changing the value of your date field.

Resources