I'm using Formik and Yup and I'm trying to create a Yup validation and I can't seem to find any help anywhere.
I have an input as a text:
<label htmlFor="loan_amount" className={styles.form_label}>
Loan Amount:
<br />
<input
type="text"
placeholder="Amount"
className={styles.loan_input}
{...formik.getFieldProps("loan_amount")}
/>
{formik.touched.loan_amount && formik.errors.loan_amount ? (
<div className={styles.error_msg}>
{formik.errors.loan_amount}
</div>
) : null}
</label>
And I'm trying to validate the text as a number so I can make use of the min() and max() attributes of Yup.number() validation.
This is my validation schema:
loan_amount: Yup.number().max((40 / 29) * parseFloat((income?.value)?.replace(/,/g, '')), `Your Maximum loan amount is ${Math.round((40 / 29) * parseFloat((income?.value)?.replace(/,/g, ''))).toLocaleString()}`).required("Loan amount is required")
The problem I have right now is that being a text field, I want to ensure that it's only numbers that are inputted. So users won't be able to input comma, dot, or any form of text.
I know that using a number input will give me exactly what I want, but I also noticed that I have this issue with a number input:
The value changes when the user scrolls. I implemented this fix but it didn't work:
<label htmlFor="loan_amount" className={styles.form_label}>
Loan Amount:
<br />
<input
type="number"
onFocus={this?.blur()}
onWheel={this?.blur()}
placeholder="Amount"
className={styles.loan_input}
{...formik.getFieldProps("loan_amount")}
/>
{formik.touched.loan_amount && formik.errors.loan_amount ? (
<div className={styles.error_msg}>
{formik.errors.loan_amount}
</div>
) : null}
</label>
I want to retain the input as a text but I need a way to specifically prevent users from typing comma or dot or any letter at all.
By the way, I've also tried using a pattern on the text input but it's not working either.
I tried this:
<label htmlFor="monthly_salary" className={styles.form_label}>
Monthly Salary:
<br />
<input
type="text"
pattern="[0-9]+"
placeholder="Input Salary"
id="gross_monthly_income"
className={styles.loan_input}
{...formik.getFieldProps("gross_monthly_income")}
/>
{formik.touched.gross_monthly_income &&
formik.errors.gross_monthly_income ? (
<div className={styles.error_msg}>
{formik.errors.gross_monthly_income}
</div>
) : null}
</label>
Any relevant help would be much appreciated so I can sort this out. I don't seem to be able to find any answers despite all the research I have done.
I also don't want to use jQuery.