I am creating a multistep form that is dynamic based on a response from a backend. The form is built in React using Formiz to accomplish this. I am trying to create the validation objects based on the information from the backend. Per the Formiz docs, custom validation would look like so:
validations={[
{
rule: (val) => val !== 0,
message: 'Need some real number here',
},
{
rule: (val) => val !== 7,
message: '7 is a lucky number but please try another one',
},
{
rule: (val) => val !== 66,
message: '66 is not a valid number',
},
]}
The information im passing in from the backend where eq can be lessThan or greaterThan, and when represents the key of the field to reference. The following means that if the value of companyStructure is soleProp then the value of ownershipPercentage must be equal 100.
{
...
key: 'ownershipPercentage',
...
validation: {
required: true,
rules: [
{
when: 'companyStructure',
value: 'soleProp',
eq: 100,
message: `Value must be equal to 100.`
}
]
},
},
My current function to create validation object that im stuck on:
const checkFieldValidation = () => {
const fieldValidation = {}
const checkIf: any = {
eq: (a: any, b: any) => a === b,
lessThan: (a: number, b: number) => a < b,
greaterThan: (a: number, b: number) => a > b
}
if (field.validation.rules) {
const rules = field.validation.rules
const fieldValue = ~~form.values[rules.when]
const conditions = Object.keys(checkIf).filter((k) => k in rules)
return conditions.every((condition) => {
return checkIf[condition](fieldValue, rules[condition])
})
}
}
What would be the correct way to take that data and return an appropriate equation based on: (val) => val !== 7?