async-validator icon indicating copy to clipboard operation
async-validator copied to clipboard

How to validate only true

Open theGABS opened this issue 7 years ago • 4 comments

I wanna validate checkbox, so I need that only true value will be acceptable. Now I try

type="enum" enum=[true] But it accept true and false

theGABS avatar Feb 10 '18 19:02 theGABS

@theGABS Hello. Did you find the solution?

vovek avatar Sep 14 '18 08:09 vovek

@theGABS, @vovek a solution:

{
  transform: value => String(value),
},
{
  type: 'enum',
  enum: ['true'],
  message: '',
},

openefit avatar Oct 18 '18 18:10 openefit

So basically to get this to work I borrowed the above example and it looks like:

    // the rules I'm passing to the validator

    const rules = {
      terms: {
        type: "enum",
        enum: ["true"],
        required: true,
        message: "*You must agree to terms",
        transform: value => value.toString()
      }
    };

  /* Inside where I'm grabbing data from the html elements
      I make sure to check for the input type 
      === checkbox then I pass in checked rather than value */
    elements
      .filter(element => !ignoredFields.includes(element.type))
      .forEach(element => {
        const { type, id, value, checked } = element;

        switch (type) {
          case "checkbox":
            fields[id] = checked;
            break;
          default:
            fields[id] = value;
        }
      });

    schema.validate(fields, (errors, validated) => submit(fields, validated));

This setup seems to work well for validating the input.

herman-rogers avatar Nov 06 '18 10:11 herman-rogers

This could be made more simple...

This can fix it, but may have breaking changes (?):

if (value !== undefined) {
      _rule2['default'][ENUM](rule, value, source, errors, options);
}

PR - https://github.com/yiminghe/async-validator/pull/164

jpenna avatar May 06 '19 06:05 jpenna