ValidatorJS isNumeric function not working properly

636 Views Asked by At

So, I want to validate a Mongoose field which should be a string containing only digits(because the first digit can be 0), and I setup a custom validator like such:

id: {
    type: String,
    required: [true, REQUIRED_VALIDATOR_ERROR_MESSAGE("ID")],
    validator: {
      validate: (value: string) => validator.isNumeric(value),
      message: (props) => `${props.value} is invalid.`,
    },
  }

but when I pass an ID which contains letters, the validation passes.

1

There are 1 best solutions below

0
On

You've got validate and validator mixed up. It should be:

id: {
    type: String,
    required: [true, REQUIRED_VALIDATOR_ERROR_MESSAGE("ID")],
    validate: {
      validator: (value: string) => validator.isNumeric(value),
      message: (props) => `${props.value} is invalid.`,
    },
  }

Here's a minimal working example:

const mongoose = require("mongoose");
const validator = require("validator");

mongoose.connect("mongodb://localhost/test", { useNewUrlParser: true });

const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", async function () {
  await mongoose.connection.db.dropDatabase();
  // we're connected!

  console.log("Connected");

  const userSchema = new mongoose.Schema({
    friends: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
    name: String,
    pid: {
      type: String,
      required: true,
      validate: {
        validator: function (value) {
          console.log("TEEEST", value);
          return validator.isNumeric(value);
        },
        message: (props) => "Prop is invalid",
      },
    },
  });

  const User = mongoose.model("User", userSchema);

  const bob = new User({ name: "Bob", friends: [], pid: "0123" });
  await bob.save();
  const natalie = new User({ name: "Natalie", friends: [bob], pid: "23" });
  await natalie.save();
  //const chris = new User({ name: "Chris", friends: [] });
  //await chris.save();
  const john = new User({ name: "John", friends: [natalie, bob], pid: "abc" });
  var valres = john.validateSync();
  console.log(valres);
  await john.save();
});

Reference: https://mongoosejs.com/docs/4.x/docs/validation.html, Custom Validators