简体   繁体   中英

SimpleSchema: How to validate an specific array

As you can see below there is an array parameter passed to the validated method. For validation I'm using SimpleSchema.

client

const url = "/articles/bmphCpyHZLhTc74Zp"
example.call({ item: url.split('/') })

server

example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        item: {
            type: [String]
        }
    }).validator(),

    run({ item }) {
        console.log(item)
    }
})

But I would like to validate a bit more specific. So the item array must have three elements. The first is empty, the second should use a value set by allowedValues and the third is an ID SimpleSchema.RegEx.Id

you can implemented is using custom schema like this. pass regex as well.

AddressSchema = new SimpleSchema({
  street: {
    type: String,
    max: 100
  },
  city: {
    type: String,
    max: 50
  },
  state: {
    type: String,
    regEx: /^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/
  },
  zip: {
    type: String,
    regEx: /^[0-9]{5}$/
  }
});

CustomerSchema = new SimpleSchema({
  billingAddress: {
    type: AddressSchema
  },
  shippingAddresses: {
    type: [AddressSchema],
    minCount: 1
  }
});

you can put it like this.

example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        item: {
            type: [CustomType],
            regEx: // your regex
        }
    }).validator(),

    run({ item }) {
        console.log(item)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM