#Dynamically change form validation rules'

13 messages · Page 1 of 1 (latest)

buoyant snow
#

Hello,

Context : I have a form (useForm) whom validate property is set with a function (it returns a dictionnary of rules, for each field). This function has a varying state and the validate rules depends on it. When I click on a button, I would like to re trigger this function in order to override the validation rules according to the changes of that state.

How could I perform that ?

Code for my form constructor :

const [isSimple, setIsSimple] = useState(simple);

const form = useForm<User>({
    initialValues: initialUserForm,
    validateInputOnChange: true,
    validate: getValidateRules(
      t,
      isSimple ?? false,
      phoneIsValid,
      sourceSite,
      register ?? false
    ),
  });

And on my button, when I click on it, I want to change the validation rules because "isSimple" changes :

<Button
  variant="gradient"
  gradient={{ from: "indigo", to: "cyan" }}
  onClick={() => {
    setIsSimple(false);
  }}
>
  {t("button.upgradeAccount")}
</Button>

Thanks in advance !

carmine ice
#

What is wrong? What does not work?

buoyant snow
carmine ice
buoyant snow
#

Isn't there any other way to do it ?

#

I would have re called the getValidateRules function

buoyant snow
#

In my case there are new fields that pops up when I click on my button and this is these fields whom have not their validate rules applied onSubmit.

To clarify, I have a "simple" and a "complete" form. My simple form has its validation rules and few inputs. My "complete" form use the same validation rules object but with 10+ more inputs.

The weird thing is that the * mandatory field mark is visible next to my fields. But I feel like the form submit button will not trigger these new fields rules'

carmine ice
buoyant snow
#

Yeah so 1 simple form and 1 complete form. I aggree with you.

#

I can't because I didn't design the application I'm working on and I don't think I have time to split it into 2 separate forms... The whole application is designed around one single form with dynamic fields on it

carmine ice