Skip to content

How validate nested models on Loopback #1698

@rkmax

Description

@rkmax

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions