sokil / php-mongo

MongoDB ODM. Part of @PHPMongoKit
http://phpmongokit.github.io/
MIT License
242 stars 46 forks source link

How to validate sub document field? #139

Open sagarguhe opened 7 years ago

sagarguhe commented 7 years ago

How do I validate sub document field? for example if I have document like this:

{
  "name": "John",
  "email": "john.doe@example.com",
  "addresses": [
    {
      "street": "field required",
      "locality": "",
      "city": "",
      "state": "",
      "country": ""
    },
    {
      "street": "field required",
      "locality": "",
      "city": "",
      "state": "",
      "country": ""
    }
  ],
  "profile": {
    "profile_picture": "myavtar.jpg",
    "skills": "php,mongo,mysql",
    "years_exp": "field required"
  }
}

In the above document I need street from addresses and years_exp from profile must be filled by the user.

So how do i validate these fields?

sokil commented 7 years ago

You need to implement Structure with validation rules, and validate this instance. Currently, embedded documents validates only on Document::set() or any method in Document that calls Structure::prepareToStore. Also it may be done manually before adding in any way to document.

Validating of embedded documents on call Document::isValid() is waiting to implement.

Samples at https://github.com/sokil/php-mongo/blob/master/README.md#validation-of-embedded-documents

sagarguhe commented 7 years ago

I found a way to validate a profile.years_exp (<--- so you have to write exactly like that) but not able to validate addresses.n.street where n stands for index of an element.

sokil commented 7 years ago

yes. If emdemmed document can be accessed directly, validation may be configured in document. To validate list of embedded documents you need to have ebbedded document class, extended from Structure. Currently this is the only way.