horprogs / Just-validate

Modern, simple, lightweight (~5kb gzip) form validation library written in Typescript, with no dependencies (no JQuery!). Support a wide range of predefined rules, async, files, dates validation, custom error messages and styles, localization. Support writing custom rules and plugins.

Home Page:https://just-validate.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Additional Rules/Validators on Groups (Not just required)

jaason435 opened this issue · comments

Is your feature request related to a problem? Please describe.
I need more validation on groups other than required. My use case (medical software) might be more complex than most, but we need the ability to add custom validators on groups to make sure that the selected value is valid in the context of other values in different fields.

Describe the solution you'd like
I think having a function "addGroup" that behaves just like "addField" would be great. Or, perhaps easier, is to add an "extraRules" parameter to "addRequiredGroup".

Btw, thanks for all your work creating this fantastic library.

Hey thanks! What other rules would be useful for groups for you case?

That's a good question. I don't think any of the standard rules for single questions would apply. The main use case is adding a custom validator. We use these often in single fields to check values in other inputs to ensure that contradicting information isn't entered.

There are plenty of examples I could provide but a good one is blood type. Say a user selects blood type A in our radio button group. That's fine. When the user moves on to the blood subtype dropdown, I want to throw up an error if they try selecting "Not applicable" or "Unknown".

Maybe I'm missing something with groups, but I would benefit greatly from just being able to write custom validators alongside 'required' rules.

I'm doing it successfully. Here's an example where I'm making sure a text input is both required and less than 100 characters in length. But we are only checking the length if a related <select> input is has had any choice but the first one which is often something like "Select one".

validator.addField('#field_id', [
  {
    rule: 'required',
    errorMessage: 'This field is required'
  },
  {
    validator: (value, context) => {
      if (document.getElementById('related_select').selectedIndex === 0) {
        return true; // default to valid if the select is still on the first choice
      }
      return value.length < 100;
    },
    errorMessage: 'error for this custom validator'
  }
])