How to use the @hapi/joi.extend function in @hapi/joi

To help you get started, we’ve selected a few @hapi/joi 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 glennjones / hapi-swagger / examples / assets / extendedjoi.js View on Github external
const Joi = require('@hapi/joi');
const customJoi = Joi.extend(joi => ({
  type: 'number',
  base: joi.number(),
  messages: {
    round: 'needs to be a rounded number', // Used below as 'number.round'
    dividable: 'needs to be dividable by {{q}}'
  },
  coerce(value, helpers) {

    // Only called when prefs.convert is true

    if (helpers.schema.$_getRule('round')) {
      return { value: Math.round(value) };
    }
  },
  /*eslint-disable */
  rules: {
github garden-io / garden / garden-service / src / config / common.ts View on Github external
export interface ObjectSchema {
    meta(keys: MetadataKeys): this
  }

  export interface StringSchema {
    meta(keys: MetadataKeys): this
    gitUrl: (params: JoiGitUrlParams) => this
    posixPath: (params?: JoiPosixPathParams) => this
  }

  export interface LazySchema {
    meta(keys: MetadataKeys): this
  }
}

export const joi: Joi.Root = Joi.extend({
  base: Joi.string(),
  name: "string",
  language: {
    gitUrl: "must be a valid Git repository URL",
    requireHash: "must specify a branch/tag hash",
    posixPath: "must be a POSIX-style path", // Used below as 'string.posixPath'
    absoluteOnly: "must be a an absolute path",
    allowGlobs: "must not include globs (wildcards)",
    relativeOnly: "must be a relative path (may not be an absolute path)",
    subPathOnly: "must be a relative sub-path (may not contain '..' segments or be an absolute path)",
    filenameOnly: "must be a filename (may not contain slashes)",
  },
  rules: [
    {
      name: "gitUrl",
      params: {
github jhnferraris / joi-mobile-number / src / index.js View on Github external
const Joi = require('@hapi/joi');
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

module.exports = Joi.extend(joi => ({
  base: joi.string(),
  name: 'string',
  language: {
    mobileNumber: 'did not seem to be a mobile number.'
  },
  rules: [
    {
      name: 'mobileNumber',
      params: {
        countryCode: joi.string().required()
      },
      validate(params, value, state, options) {
        try {
          const number = phoneUtil.parseAndKeepRawInput(value, params.countryCode);
          // getNumberType === 1 means it is a Mobile Number
          // https://github.com/ruimarinho/google-libphonenumber/blob/master/src/phonenumberutil.js#L916
github wso2 / carbon-apimgt / features / apimgt / org.wso2.carbon.apimgt.publisher.feature / src / main / resources / publisher / source / src / app / data / APIValidation.js View on Github external
*/
const roleSchema = Joi.extend((joi) => ({
    base: joi.string(),
    name: 'systemRole',
    rules: [
        {
            name: 'role',
            validate(params, value, state, options) { // eslint-disable-line no-unused-vars
                const api = new API();
                return api.validateSystemRole(value);
            },
        },
    ],
}));

const scopeSchema = Joi.extend((joi) => ({
    base: joi.string(),
    name: 'scopes',
    rules: [
        {
            name: 'scope',
            validate(params, value, state, options) { // eslint-disable-line no-unused-vars
                const api = new API();
                return api.validateScopeName(value);
            },
        },
    ],
}));

const userRoleSchema = Joi.extend((joi) => ({
    base: joi.string(),
    name: 'userRole',
github stelace / stelace / src / util / validation.js View on Github external
extractDataFromObjectId,
  platformZones
} = require('stelace-util-keys')

const UUID_V4_REGEX = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i

function isUUIDV4 (value) {
  return typeof value === 'string' && UUID_V4_REGEX.test(value)
}

/**
 * Joi does not coerce strings to objects and arrays anymore since v16
 * so we restore this behavior manually.
 * https://github.com/hapijs/joi/issues/2037, "Array and object string coercion"
 */
const customJoi = Joi.extend(
  {
    type: 'object',
    base: Joi.object(),
    coerce: {
      from: 'string',
      method (value, helpers) {
        if (typeof value !== 'string') return
        if (value[0] !== '{' && !/^\s*\{/.test(value)) return

        try {
          return { value: Bourne.parse(value) }
        } catch (ignoreErr) { }
      }
    }
  },
  {
github badges / shields / services / validators.js View on Github external
'use strict'

const { semver, semverRange } = require('joi-extension-semver')
const Joi = require('@hapi/joi')
  .extend(semver)
  .extend(semverRange)

const optionalNonNegativeInteger = Joi.number()
  .integer()
  .min(0)

module.exports = {
  optionalNonNegativeInteger,

  nonNegativeInteger: optionalNonNegativeInteger.required(),

  anyInteger: Joi.number()
    .integer()
    .required(),
github tlivings / enjoi / lib / resolver.js View on Github external
for (const schema of params.items) {
                        Joi.validate(value, schema, options, (err) => {
                            error = err;
                        });
                        if (error) {
                            const details = error.details[0];
                            return this.createOverrideError(details.type, details.context, { path : details.path }, options, details.message);
                        }
                    }
                    return value;
                }
            }]
        });

        this.joi = Joi.extend(extensions);
    }
github Saeris / graphql-scalars / src / postalCode.js View on Github external
import { GraphQLScalarType, GraphQLError, Kind  } from "graphql"
import * as BaseJoi from "@hapi/joi"
import joiPostalCode from "joi-postalcode"

const Joi = BaseJoi.extend(joiPostalCode)

const countries = [`US`, `GB`, `DE`, `CA`, `FR`, `IT`, `AU`, `NL`, `ES`, `DK`, `SE`, `BE`, `IN`]

const validate = value => {
  Joi.assert(value, Joi.string(), new TypeError(`Value is not string: ${value}`))
  Joi.assert(value, [...countries.map(country => Joi.string().postalCode(country))], new TypeError(`Value is not a valid postal code: ${value}`))
  return value
}

export const PostalCodeScalar = `scalar PostalCode`

export const PostalCode = new GraphQLScalarType({
  name: `PostalCode`,

  description: `A field whose value conforms to the standard postal code formats for United States, United Kingdom, Germany, Canada, France, Italy, Australia, Netherlands, Spain, Denmark, Sweden, Belgium or India.`,
github ArkEcosystem / core / packages / core-api / src / handlers / shared / schemas / order-by.ts View on Github external
import Joi from "@hapi/joi";

const customJoi = Joi.extend(joi => ({
    base: joi.any(),
    name: "orderBy",
    language: {
        format: "needs to match format :",
        iteratee: "needs to have an iteratee included in: [{{valid}}]",
        direction: 'needs to have a direction of either "asc" or "desc"',
    },
    rules: [
        {
            name: "valid",
            params: {
                validIteratees: joi
                    .array()
                    .min(1)
                    .items(Joi.string())
                    .required(),
github xogroup / felicity / lib / joi.js View on Github external
'use strict';

const Joi               = require('@hapi/joi');
const JoiDateExtensions = require('@hapi/joi-date');

module.exports = Joi.extend(JoiDateExtensions);