Lift Record: empty value for required field but no validation errors

若如初见. 提交于 2019-12-12 04:41:16

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22395669/lift-record-empty-value-for-required-field-but-no-validation-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!