0

How to Check "invalid numbers" Validations in mongoose? Is there any special method or keyword available? Model.js given below?

Model.js


const Schema = mongoose.Schema;
const userSchema = new Schema({
  Username: {
    type: String,
    required: true
  },
  Password: {
    type: String,
    required: true
  }
});

userSchema.pre('save', async function (next) {
  try {
    const user = this;

    if (!user.isModified('Password')) {
      next();

    }

    const salt = await bcrypt.genSalt(10);
    const passwordHash = await bcrypt.hash(this.Password, salt);
    this.Password = passwordHash;
    next();
  } catch (error) {
    next(error);
  }
});


module.exports = User;
3
  • 1
    What kind of number Commented Jan 14, 2020 at 9:01
  • 2
    Hi, and welcome to stack overflow, being specific about your question would help other to answer your question, you could also check following post: stackoverflow.com/help/how-to-ask Commented Jan 14, 2020 at 9:14
  • Any type of numer Commented Jun 22, 2020 at 6:42

1 Answer 1

1

You can do it custom validators of mongoose: https://mongoosejs.com/docs/validation.html#custom-validators For example, if you want your password to contain only numbers(using RegEx):

const Schema = mongoose.Schema;
const userSchema = new Schema({
  Username: {
    type: String,
    required: true
  },
  Password: {
    type: String,
    required: true,
    validate: {
       validator: function(v) {
          return /^[0-9]*$/gm.test(v); // this is RegEx of validation only numbers : https://www.regextester.com/21
       },
       message: props => `${props.value} should be a number!`
    },
  }
});

userSchema.pre('save', async function (next) {
  try {
    const user = this;

    if (!user.isModified('Password')) {
      next();

    }

    const salt = await bcrypt.genSalt(10);
    const passwordHash = await bcrypt.hash(this.Password, salt);
    this.Password = passwordHash;
    next();
  } catch (error) {
    next(error);
  }
});


module.exports = User;```
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.