Simple required field validation using jQuery

Sometimes, you work within the constraints of an existing application, trying to change as little as possible. So when a client had a very simple (two field) form, that showed up as a Bootstrap modal, and I needed to make sure the user didn’t click the submit button until they filled out all the fields, I simply dropped in the following JavaScript.

$(document).on('change keyup', '[required]', function() {
		var targetForm = $($('[required]')[0].form);
		var requiredOk = targetForm.find('[required]').filter(function () { return $(this).val().length == 0; }).length == 0;
		targetForm.find(':submit').prop('disabled', !requiredOk);

I then marked up my form fields by adding required property to each field that was required to be true. A simplified example follows.

<form id="form1">
  <input type="text" id="input1" required /><br />
  <textarea id="textarea1" required></textarea><br />
  <button type="submit" disabled>

Now, your submit buttons will automatically disable/enable. It doesn’t work in more complex forms with other field types, but I did start off by saying this was a “simple” solution, after all.

JSFiddle here:

MVC model validation with Castle Validator

The ASP.Net MVC framework comes with built-in model validation using the Data Annotation validators. Unfortunately, the Data Annotations aren’t as robust as other validation libraries, such as the Castle Validators.

Implementing a custom model validator (for server-side validation — client-side validation requires more than is covered in this post), you need to write an implementation of the ModelValidator and ModelValidatorProvider classes that support the Castle Validators.

An example of how to do this follows. Though it hasn’t been fully tested, it worked for a handful of situations I experimented with. Use this as a starting point for your own server-side model validator implementation. Continue reading