Loopback: How validate nested models on Loopback

Created on 24 Sep 2015  路  3Comments  路  Source: strongloop/loopback

I'm confused if nested validation it's supported, how it works and if it's possible do the situation described below

I have the following models

  • Customer based on PersistedModel

    • contact property type ContactInfo

    • address property type Address

    • ...

  • ContactInfo based on Model

    • emailAddress property type string

    • phoneNumber property type string

    • firstName property type string

    • lastName property type string

  • Address based on Model

    • street property type string

    • city property type string

    • state property type string

    • zipCode property type string

I also want to validate

  • contact.emailAddress is unique, but not required
  • contact.phoneNumber is unique, but not required

I want know if it's possible validate only when it's present in the payload and using the default validators e.g. validatesUniquenessOf

Currently I've added a validator

//contact-info.js
module.exports = function(ContactInfo) {
  ContactInfo.validatesUniquenessOf('phoneNumber', {message: 'You can\'t use this number', allowNull: true});
};

for testing proposes I have in my database a document in the Customer collection

{
  "_id": ObjectId("56003b7901caa9db416eca5f"),
  "contact": {
    "firstName" "Bob",
    "lastName" "SquarePants",
    "phoneNumber": "555-5678"
  }
}

and sent following request

POST /api/Customers
{
  "contact": {
    "firstName" "Patrick",
    "lastName" "Star",
    "phoneNumber": "555-5678"
  }
}

the expected result is a 422 response but I get a 200, btw I think it should be a 201

triaging

Most helpful comment

Has this been implemented in latest versions ? If yes, can you share link for documentation or examples.

All 3 comments

I don't believe we support deep validation. See https://github.com/strongloop/loopback/issues/300#issuecomment-44973571

For future reference, please post questions to https://groups.google.com/forum/#!forum/loopbackjs. See https://github.com/strongloop/loopback/wiki/Questions for more details.

Has this been implemented in latest versions ? if not, are there are any future plans to implement this? Happy to pick this up if this is still an open feature

Has this been implemented in latest versions ? If yes, can you share link for documentation or examples.

Was this page helpful?
0 / 5 - 0 ratings