javascriptmeteorsimple-schema

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


Solution

  • 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)
        }
    })