sokil/php-mongo

How to validate sub document field?

sagarguhe opened this issue · 3 comments

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

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

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

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.