A long time ago, I asked about systems for form validation that aren’t “model-based”. By “model-based validation”, I mean that the rules for whether a certain sort of input is acceptable are declared in (or attached to) a domain model that the form is operating on. This is the way that ActiveRecord (Rails) and Magritte (Seaside) work.

I don’t like the whole approach, for reasons I discussed in my earlier post. It breaks down when you want to edit an object in stages, and you end up managing lots of UI-related things down in the model code. But forms are boring and validation can be tedious, which is why frameworks like these have been built in the first place.

What I really wanted was a set of simple helpers that made this work easier — a “less is more” approach to the problem. That didn’t exist (at least in Seaside), so I built my own.

It’s called “Mold”, and it’s available both on SqueakSource and in the Cincom Public Repository. The name is a play on words: it’s a synonym for “form”, but it makes most normal people think of green fuzzy fungae.

Design Principles

In building Mold, I had several specific goals:

No new components. I didn’t want to have to remember to add anything to #children just because I was using this framework. Keep track of what the user types, even if it’s not valid, to allow for easy correction of mistakes. “r56” might not parse to a valid integer, but it’s better to let the user delete the “r” than force it to “0” and complain at him. Emit real objects, not just strings. If I’m asking the user to enter a date or a time, I want a Date or Time object when all is said and done. Use block-based validation criteria to keep things flexible. Error messages should allow blocks to be used too, so that your can put dynamic behavior in there too. Correlate errors closely to the problematic fields. It’s more helpful to show an error message right next to the field than to show it at the top of the page. Strip leading and trailing whitespace, and convert empty strings to nil. Semantically, an empty string almost always means “nothing” and is rarely worth keeping around. Callback or dictionary-like access to valid data. Sometimes you want to grab bits of data out of the form by name, but most of the time it’s nice to have the form dump valid results right into your model in one step. Don’t require all-or-nothing use. I might want to use the helpers to build part of the form, but handle other parts myself. It should be possible to completely customize the look of each form without sacrificing the benefits of the framework.

The Basics

To use a mold, you typically instantiate and hold a Mold in an instance variable of your component. For a simple form with no underlying model, you might build the mold when the component is initialized.

initialize super initialize. self buildMold

For editors with a model under the hood, it makes sense to build the mold when the model is passed in:

account: anAccount account := anAccount. self buildMold

The mold itself has a canvas-like API for declaring a form’s inputs and validation conditions.

buildMold mold := Mold new. (mold stringField) label: 'Username:'; on: #username of: account; beRequired. (mold passwordField) label: 'Password:'; on: #password of: account; beRequired.

In this simple form, we only ask for 2 things, and we hook them directly to accessor methods on the model using #on:of:. This works just like it does in a regular Seaside form, and behind the scenes it simply creates a callback block. You can also create a custom callback block yourself.

When it comes time to render your form, you have to hand the `html` canvas to the mold, and then it gives you lots of handy shortcuts. Basic use will look something like this:

renderContentOn: html html form: [mold canvas: html. mold paragraphs. (html submitButton) callback: [self save]; value: 'Save']

This usage tells the mold to render those fields as HTML paragraphs, like so:

The labels are real HTML <label> tags, and each group is a single paragraph (<p><label for=”…”>Username:</label><br /><input … /></p>) We could have also used #tableRows:

renderContentOn: html html form: [mold canvas: html. html table: [mold tableRows. html tableRow: [html tableData; tableData: [(html submitButton) callback: [self save]; value: 'Save']]]]

It’s more work to build the framework around the table, but the end result looks like this:

These are the only two “canned” looks for an entire mold, but it’s also possible to take the reins yourself and ask Mold to render single components for a completely custom look. More on that below.

The final step in using this mold is hooking up the #save callback. Let’s assume you’re using the super cool SandstoneDb framework to save your models:

save mold isValid ifFalse: [^self]. account save: [mold save]. self answer

That’s all there is to it. The mold can tell you whether its inputs were valid, and if not, it will display error messages on subsequent renders. If it is valid, telling it to save will fire all of its callbacks, thereby applying the changes to the underlying model.

The way I use Glorp, the save method looks nearly identical, but you have to register your model object in a unit of work. Using the mold’s save actions to apply your changes inside the unit of work keeps Glorp’s deep dark change-tracking voodoo working.

save mold isValid ifFalse: [^self]. self database inUnitOfWorkDo: [:db | db register: account. mold save]. self answer

Improving Looks

Let’s look at what interactions with the mold look like. We declared that both fields should be required, so if you don’t type anything (and just click “save”) you’ll see error messages by each field:

This form is a little bland, and it’s spacing is awkward because Mold uses unordered lists inside those table cells. Let’s apply some simple CSS:

style ^' label.required { font-weight: bold; } label.required:after { content: "*"; color: red; } .error { background-color: #ecc; } .errors { color: red; margin: 0; } '

That looks better — we call attention to the required fields, error messages are shown in red, and fields with errors have a reddish background too. Let’s make the username field a little wider. We’ll do this by adding a #customize: block in the mold declaration:

buildMold mold := Mold new. (mold stringField) label: 'Username:'; on: #username of: account; customize: [:tag | tag size: 40]; beRequired. (mold passwordField) label: 'Password:'; on: #password of: account; beRequired.

Now the next time we build one of these components (remember, we built the mold when the component was initialized, so it won’t automatically be rebuilt just from a browser refresh), our form will look like this:

More Conditions and Inter-Relationships

Let’s modify the field a little further. If we require usernames have to be at least 3 characters long and passwords to have a digit in them, we need some more conditions on these fields. We should also make the user type the password twice to guard against typos.

buildMold | passwordField confirmPasswordField | mold := Mold new. (mold stringField) label: 'Username:'; on: #username of: account; customize: [:tag | tag size: 40]; beRequired; addCondition: [:input | input size >= 3] labeled: 'Usernames must be at least 3 characters long'. (passwordField := mold passwordField) label: 'Password:'; on: #password of: account; beRequired; addCondition: [:input | input matchesRegex: '.*\d.*'] labeled: 'Please make sure your password has at least one number in it'. (confirmPasswordField := mold passwordField) label: 'Confirm Password:'; beRequired. passwordField addCondition: [:input | input = confirmPasswordField input] labeled: 'Passwords did not match'. confirmPasswordField addCondition: [:input | input = passwordField input] labeled: 'Passwords did not match'.

There’s a bit more going on here, but it’s all pretty straightforward to use. A few things to note:

We’ve added conditions on required fields, so these won’t be evaluated unless some input is actually given. If these fields were optional, we’d have to check `input` to make sure it wasn’t nil before asking it for its size. The fields can refer to each other, even out of order. We didn’t technically have to put conditions on both fields, but it makes the error messages look nicer if we do. There is no callback on the confirmation field. It simply exists for use by the main password field. When referring to the other fields, we asked them for their #input. This is the string the user typed (having been trimmed of leading and trailing whitespace and converted to nil if it was empty). We could have also asked for its #value, but the value is only valid when the field is valid (incidentally, fields also understand #isValid). The resulting form looks like this: One “Gotcha” Under the hood, the out-of-order field processing is done with a hidden input with a low-priority callback. This is hooked up when the mold’s canvas is set (mold canvas: html). The callback doesn’t fire until all of the other input’s callbacks are processed, but it fires before the action callback from the button. That means that you must set the mold’s canvas inside the form: [] block. Failure to do so will mean that your validations never get run, and the mold will always answer `true` when sent #isValid. There might be a cleaner way to do this, but I haven’t found it yet. Advanced Moldiness Mold fields can also be given a symbol for a key, which lets you refer to them directly. This makes custom rendering possible, with messages like: mold paragraph: #confirmPassword. mold widget: #username mold errors: #someOtherField When you use #on:of: to hook up a callback, the key for the widget is automatically assigned to the selector you passed as the first argument. You can also set the key directly using #key:, and a subsequent send of #on:of: will not clobber it. Error messages can also be blocks, which means that you can put the user’s input into the error message: (mold stringField) key: #username; addCondition: [:input | (Account find: [:each | each username = input]) notNil] labeled: [:input | 'The username "', input, '" is already taken']. There’s also no reason why you can’t add two or more molds to a component — say, one for basic settings and one for advanced settings that aren’t shown unless the user clicks “more choices”. Adding fields is a matter of adding a new protocol on Mold and optionally a new Field subclass. I say “optionally” because some fields can be built as specialized versions of existing fields, like a string field with a default validation rule. The emailField is currently implemented this way. In Summary

I know not everyone believes that model-based validation is a problem. But if all you’re looking for is a simple way to build a custom form, you might find Mold helpful. We’ve been using it internally for nearly a year, so I figured it was time to touch it up and share it.

Mold makes no requirements of your components or your model objects. It doesn’t use any metadata; it allows you to choose how you want each form rendered; and it doesn’t require you to use it to build the entire form. It’s just a helper, and it gets out of your way when you don’t need it.

Just don’t leave it alone in a cool dark place for too long, or it might start to grow on you. :)