DRY user-input validation (clientside, serverside) using JSON-schema

前端 未结 1 1979
星月不相逢
星月不相逢 2021-02-04 13:07

As part of a extensive test-case, I\'m building an ajax-based CMS-like application which provides CRUD-functionality on various documenttypes, e.g: articles, tags, etc.

相关标签:
1条回答
  • 2021-02-04 13:38

    It is very possible and one of the most gratifying things to have a single definition of validations in one place (per model) on the server that can then generate appropriate JS for client-side and AJAX-based validations.

    Yii framework for PHP has a fantastic architecture for accomplishing this in an elegant way that stores all the validation rules together in the model (divvied up into appropriate "scenarios" as needed). From there, it's a matter of flipping a few switches to make a particular form client-side or AJAX-validateable. I believe Yii's interfaces for this were based on Rails.

    Anyway I would highly recommend checking out the following key points from Yii's design; even if you don't know PHP, you can use this for inspiration:

    • CModel::rules() => The DRY source for model validation rules
    • CActiveForm => Used to generate form elements based on model attributes
      • See for example CActiveForm::textField()
    • CValidator => Base class for validators which provisions for the ability to client-validate

    I think it's wise to pursue DRY validation rule declaration and in my experience it is not at all unrealistic to achieve that 100% and still have rich forms—and rich validation rules. (And boy will you love life when you don't have to manage all that client-validate JS...)

    Hope this helps.

    0 讨论(0)
提交回复
热议问题