skip to Main Content
import mongoose from "mongoose";
const mobileNoSchema = mongoose.Schema(
mobileNo: {
            type: String,
            // min: [10, "no is < 10"],
            // max: [10, "no is > 10"],
            validate: {
                validator: function(v) {
                    if(v.length === 10) return true;
                    return /d{10}/.test(v);
                },
                message: props => `${props.value} is not a valid phone number!`
            }   
        }
);

const Mobile= mongoose.model("mobile", mobileNoSchema);
export default Mobile;

My code is not working if i try using min and max validating only for max value
can anybody help me out

2

Answers


  1. min and max are validators for type Number. They are used to compare Number values, not the lengths of the strings. If you want to compare lengths, use minLength and maxLength validators. Also, if you need to check whether all characters are numbers use match validator like this:

    import mongoose from "mongoose";
    const mobileNoSchema = mongoose.Schema(
    mobileNo: {
                type: String,
                minLength: [10, "no should have minimum 10 digits"],
                maxLength: [10, "no should have maximum 10 digits"],
                match: [/d{10}/, "no should only have digits"]
    );
    const Mobile= mongoose.model("mobile", mobileNoSchema);
    export default Mobile;
    

    Documentation link.

    Login or Signup to reply.
  2. Try with this condition below:

    const yourSchema = new mongoose.Schema({
      phoneNr: {
        type: String,
        match: /^(()?d{3}())?(-|s)?d{3}(-|s)d{4}$/,
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search