How to use the yup.addMethod function in yup

To help you get started, we’ve selected a few yup examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / types / yup / yup-tests.ts View on Github external
// reach function
const schema1 = yup.object().shape({
    nested: yup.object().shape({
        arr: yup.array().of(yup.object().shape({ num: yup.number().max(4) })),
    }),
});
reach(schema1, 'nested.arr.num');
reach(schema1, 'nested.arr[].num');

// isSchema function
const isSchemaResult1: boolean = isSchema(schema1);
const isSchemaResult2: boolean = isSchema({});

// addMethod function
yup.addMethod(yup.number, 'minimum', function(this, minValue: number, message: string) {
    return this.min(minValue, message);
});
yup.addMethod(yup.date, 'newMethod', function(this: yup.DateSchema, date: Date, message?: string) {
    return this.max(date, message);
});

// ref function
const schema2 = yup.object().shape({
    baz: yup.ref('foo.bar'),
    foo: yup.object().shape({
        bar: yup.string(),
    }),
    x: yup.ref('$x'),
});

let ref: yup.Ref = yup.ref('foo.bar');
github TheThingsNetwork / lorawan-stack / pkg / webui / lib / yup-extensions.js View on Github external
self
        .transform(function(value) {
          if (self.isType(value) && Boolean(value)) {
            return value
          }

          return null
        })
        .nullable(true)
    })
  }
}

Yup.nullableString = () => new NullableStringSchemaType()

Yup.addMethod(Yup.string, 'emptyOrLength', function(exactLength, message) {
  // eslint-disable-next-line no-invalid-this
  return this.test(
    'empty-or-length',
    message,
    value => !Boolean(value) || value.length === exactLength,
  )
})

export default Yup
github jurkian / react-bank / web / src / tools / validations / YupCustomValidations.js View on Github external
import * as Yup from 'yup';

// Check for exact length of string or number
Yup.addMethod(Yup.mixed, 'length', function(length, msg) {
   return this.test({
      name: 'length',
      message: msg,
      test: value => value && value.toString().length === length
   });
});
github kristianmandrup / schema-to-yup / packages / yup-validator-bridge / lib / extend-yup-api.ts View on Github external
Object.keys(constraints).map(key => {
    let { testName, optsKey, validatorName, logging } = constraints[key];
    const fullValidatorName = createValidatorName(validatorName, key);
    testName = createTestName(testName, key);

    // See https://github.com/jquense/yup#yupaddmethodschematype-schema-name-string-method--schema-void
    Yup.addMethod(string, key, (args: any = {}) => {
      const { message } = args;
      const opts = args[optsKey];
      return string().test(testName, message, value => {
        // return this.transform(value => {
        const { path, createError } = Yup;
        // [value] - value of the property being tested
        // [path]  - property name,
        // ...
        let validatorFn = validator[fullValidatorName];
        validatorFn = validatorFn || fallBackFnMap[fullValidatorName];

        if (typeof validatorFn !== "function") {
          throw Error("No method named ${validatorName} on validator");
        }
        const valid = validatorFn(value, opts);
        if (logging === true) {
github strapi / strapi / packages / strapi-plugin-content-type-builder / admin / src / containers / FormModal / utils / forms.js View on Github external
return this.test('hasNotEmptyValues', message, function(array) {
    return !array.some(value => isEmpty(value));
  });
});

yup.addMethod(yup.string, 'isAllowed', function(message) {
  return this.test('isAllowed', message, function(string) {
    if (!string) {
      return false;
    }

    return !RESERVED_NAMES.includes(toLower(trim(string)));
  });
});

yup.addMethod(yup.string, 'isInferior', function(message, max) {
  return this.test('isInferior', message, function(min) {
    if (!min) {
      return false;
    }

    if (Number.isNaN(toNumber(min))) {
      return true;
    }

    return toNumber(max) >= toNumber(min);
  });
});

const ATTRIBUTES_THAT_DONT_HAVE_MIN_MAX_SETTINGS = [
  'boolean',
  'date',
github arcanis / clipanion / sources / demos / advanced.ts View on Github external
import {Readable, Writable} from 'stream';
import * as yup             from 'yup';

import {Cli, Command}       from '../advanced';

type Context = {
    cwd: string;
    stdin: Readable;
    stdout: Writable;
    stderr: Writable;
}

yup.addMethod(yup.object, `atMostOneOf`, function (list: Array) {
    return this.test({
        name: `atMostOneOf`,
        message: `\${path} must only have at most one of these keys: \${keys}`,
        params: { keys: list.join(`, `) },
        test: value => value == null || list.filter(f => !!value[f]).length <= 1,
    });
});

declare module 'yup' {
    interface Schema {
        atMostOneOf(keys: string[]): this;
    }
}

class YarnDefaultDefinitions extends Command {
    @Command.Path(`--clipanion=definitions`)
github calluswhatyouwant / musicritic / src / components / common / validator / UserValidator.js View on Github external
const equalTo = (ref: any, msg: any) => {
    const { path } = ref.path;
    return Yup.mixed().test({
        name: 'equalTo',
        message: msg || `${path} must be the same as ${ref}`,
        params: {
            reference: ref.path,
        },
        test(value) {
            return value === this.resolve(ref);
        },
    });
};

Yup.addMethod(Yup.string, 'equalTo', equalTo);

export const usernameValidator = () => {
    const min = 6;
    const max = 12;
    return Yup.string()
        .required('Username is required.')
        .min(6, `Username must have at least ${min} characters.`)
        .max(12, `Username must have up to ${max} characters.`);
};

export const emailValidator = () => Yup.string()
    .email('Invalid email address.')
    .required('Email is required.');

export const passwordValidator = () => {
    const min = 6;
github yugabyte / yugabyte-db / managed / ui / src / components / config / PublicCloud / Kubernetes / CreateKubernetesConfiguration.js View on Github external
const initialValues = {
      providerType: null,
      accountName: "",
      serviceAccount: "",
      pullSecret: null,
      regionCode: "",
      zoneLabel: "",
      kubeConfig: null,
      imageRegistry: "",
      storageClasses: "",
      regionList: [],
      zoneOverrides: "",
    };

    Yup.addMethod(Yup.array, 'unique', function (message, mapper = a => a) {
      return this.test('unique', message, function (list) {
        return list.length === new Set(list.map(mapper)).size;
      });
    });

    const validationSchema = Yup.object().shape({
      accountName: Yup.string()
      .required('Config name is Required'),

      serviceAccount: Yup.string()
      .required('Service Account name is Required'),

      kubeConfig: Yup.mixed().nullable(),

      pullSecret: Yup.mixed(),
github strapi / strapi / packages / strapi-plugin-content-type-builder / admin / src / containers / FormModal / utils / forms.js View on Github external
return false;
    }

    return !alreadyTakenAttributes.includes(
      typeof validator === 'function' ? validator(string, category) : string
    );
  });
});

yup.addMethod(yup.array, 'hasNotEmptyValues', function(message) {
  return this.test('hasNotEmptyValues', message, function(array) {
    return !array.some(value => isEmpty(value));
  });
});

yup.addMethod(yup.string, 'isAllowed', function(message) {
  return this.test('isAllowed', message, function(string) {
    if (!string) {
      return false;
    }

    return !RESERVED_NAMES.includes(toLower(trim(string)));
  });
});

yup.addMethod(yup.string, 'isInferior', function(message, max) {
  return this.test('isInferior', message, function(min) {
    if (!min) {
      return false;
    }

    if (Number.isNaN(toNumber(min))) {
github strapi / strapi / packages / strapi-plugin-content-manager / admin / src / containers / EditViewDataManagerProvider / utils / schema.js View on Github external
isEmpty,
  isNaN,
  toNumber,
} from 'lodash';
import * as yup from 'yup';
import { translatedErrors as errorsTrads } from 'strapi-helper-plugin';

yup.addMethod(yup.mixed, 'defined', function() {
  return this.test(
    'defined',
    errorsTrads.required,
    value => value !== undefined
  );
});

yup.addMethod(yup.array, 'notEmptyMin', function(min) {
  return this.test('notEmptyMin', errorsTrads.min, value => {
    if (isEmpty(value)) {
      return true;
    }
    return value.length >= min;
  });
});

yup.addMethod(yup.string, 'isInferior', function(message, max) {
  return this.test('isInferior', message, function(value) {
    if (!value) {
      return true;
    }

    if (Number.isNaN(toNumber(value))) {
      return true;