Yup: [Feature request] Mongo ObjectId validation

Created on 18 Feb 2019  路  1Comment  路  Source: jquense/yup

Add the following schema types:

  • objectId()

This should be used as a type to validate object Id's

Example

We want to have a field with an objectId

var schema = yup
    .objectId()

Most helpful comment

This isn't a great fit for the core library since it's server specific and requires bson. Luckily tho it is easy to add yourself for your application.

should be something like this:

const { ObjectId } = require('bson');

class ObjectIdSchema extends yup.mixed {
  constructor() {
    super({ type: 'objectId' });

    this.withMutation(schema => {
      schema.transform(function(value) {
        if (this.isType(value)) return value;
        return new ObjectId(value);
      });
    });
  }

  _typeCheck(value) {
    return ObjectId.isValid(value);
  }
}

yup.objectId = () => new ObjectIdSchema();

>All comments

This isn't a great fit for the core library since it's server specific and requires bson. Luckily tho it is easy to add yourself for your application.

should be something like this:

const { ObjectId } = require('bson');

class ObjectIdSchema extends yup.mixed {
  constructor() {
    super({ type: 'objectId' });

    this.withMutation(schema => {
      schema.transform(function(value) {
        if (this.isType(value)) return value;
        return new ObjectId(value);
      });
    });
  }

  _typeCheck(value) {
    return ObjectId.isValid(value);
  }
}

yup.objectId = () => new ObjectIdSchema();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

cfteric picture cfteric  路  3Comments

laurazenc picture laurazenc  路  3Comments

jgcmarins picture jgcmarins  路  4Comments

haddyo picture haddyo  路  3Comments

seanbruce picture seanbruce  路  3Comments