I have a form created with React hook form and input field thant can have 2 different values: a pec email or a SDI code with different validation.
I get error with validation: keep telling me that sdi should be 7 characters but the name is set to "pecEmail". Also at page load "name" is set to "sdiCode" but if an email is already there, should be "email". It changes when I click the input. I tried to pass the name field in register but I lost all the validation
ref={register(isPec ? 'pecEmail' : 'sdiCode', {
code here:
const [isPec, setIsPec] = useState()
const sdiOrPec = watch(['sdiCode', 'pecEmail'])
useEffect(() => {
setIsPec(
(sdiOrPec.sdiCode && sdiOrPec.sdiCode.includes('@')) ||
(sdiOrPec.pecEmail && sdiOrPec.pecEmail.includes('@'))
)
}, [watch])
<div className='input-container'>
<div
className={`input-container__item ${
errors[isPec ? 'pecEmail' : 'sdiCode'] && 'has-error'
}`}
>
<label>{t('components.BillingInfoForm.sdiLabel')}</label>
<input
type='text'
name={!isPec ? 'sdiCode' : 'pecEmail'}
defaultValue={
get(billingInformations, 'sdiCode')
? get(billingInformations, 'sdiCode')
: get(billingInformations, 'pecEmail')
? get(billingInformations, 'pecEmail')
: ''
}
placeholder={t('components.BillingInfoForm.sdiPlaceholder')}
ref={register({
maxLength: {
value: isPec ? 320 : 7,
message:
!isPec &&
t('components.BillingInfoForm.sdiMessageError'),
},
minLength: {
value: isPec ? 3 : 7,
message:
!isPec &&
t('components.BillingInfoForm.sdiMessageError'),
},
validate: {
value: (value) => {
if (isPec && sdiOrPec.pecEmail) {
return (
isEmailValid(sdiOrPec.pecEmail) ||
t('components.SignupForm.emailError')
)
}
},
},
})}
/>
{errors[isPec ? 'pecEmail' : 'sdiCode'] && (
<small>
{errors[isPec ? 'pecEmail' : 'sdiCode'].message}
</small>
)}
</div>
</div>
Thanks