Pavel
Pavel

Reputation: 35

Depending fields validation

I have two password fields that, among other rules, have to be equal for the form to be valid.

<form onSubmit="resetPassword">
    <ValidationGroup valid-bind="$page.formvalid"  >
        <FlexCol>
            <TextField
                value-bind="$page.password1"
                label="Password 1"
                inputType="password"
                required
                validationRegExp={/(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/}
                minLength="6"
                onValidate="validatePasswordsEqual"
            />
            <TextField
                value-bind="$page.password2"
                label="Password 2"
                inputType="password"
                required
                validationRegExp={/(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/}
                minLength="6"
                onValidate="validatePasswordsEqual"
            />
            <Button
                submit
                disabled-expr="!{$page.formvalid}"
                text="Reset Password"
            />
        </FlexCol>
    </ValidationGroup>
</form>

However, the validatePasswordsEqual runs only for the currently edited field, leaving the other field always unequal. I tried using store.notify() from inside the validatePasswordsEqual, but without success.

How can I cause validation on both fields at the same time?

Upvotes: 2

Views: 45

Answers (1)

Marko
Marko

Reputation: 5454

You can use the validationParams field to trigger the validation if a value in another field changes.

<TextField
   value-bind="$page.password1"
   label="Password 1"
   inputType="password"
   validationParams={{ password2: { bind: '$page.password2 }}
   required
   validationRegExp={/(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/}
   minLength="6"
   onValidate="validatePasswordsEqual"
/>

The third argument provided to the onValidate callback will be the calculated value of validationParams.

Upvotes: 1

Related Questions