Question

I've been trying to figure out how to do this without manually defining a validation but without any success so far.

I have a StringField

class Foo private() extends MongoRecord[Foo] with ObjectIdKey[Foo] {
  ...
  object externalId extends StringField(this, 255) {
    // none of these seem to have any effect on validation whatsoever:
    override def optional_? = false
    override def required_? = true
    override def defaultValueBox = Empty
  }
  ...
}

Now when I call .validate on a Foo, it returns no errors:

val foo = Foo.createRecord
foo.validate match {
  case Nil => foo.save
  ...
}

...and the document is saved into the (mongo) DB with no externalId.

So the question is: is there any way at all to have Lift automatically validate missing fields without me having to manually add stuff to validations?

EDIT: am I thinking too much in terms of the type of productivity that frameworks like Django and Rails provide out of the box? i.e. things like basic and very frequent validation without having to write anything but a few declarative attributes/flags. If yes, why has Lift opted to not provide this sort of stuff out of the box? Why would anybody not want .validate to automatically take into consideration all the def required_? = true/def optional_? = false fields?

Was it helpful?

Solution

As far as I'm aware, there isn't a way for you to validate a field without explicitly defining validations. The reason that optional_? and required_? don't provide validation is that it isn't always clear what logic to use, especially for non String fields. The required_? value itself is used by Crudify to determine whether to mark the field as required in the produced UI, but it's up to you to provide the proper logic to determine that the requirement is satisfied.

Validating the field can be as easy as

override def validations = super.validations :: valMinLen(1, "Required!")

Or see the answer to your other question here for how to create a generic Required trait.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top