xVal Custom Rules on empty form fields

Sep 19, 2009 at 1:43 PM


i'm using DataAnnotations for server-side validation and jquery validate for client-side validation purposes. I want to create a client-side xVal custom rule for a form field that would trigger the javascript validation function even if the field is empty (and i don't want to use DataAnnotations [Required] attribute). So far, the function is being triggered only if the field is not empty (has at least one character).

Is there a solution for this?

Thanks in advance,


Mar 2, 2010 at 12:17 PM
Edited Mar 2, 2010 at 12:19 PM

I don't know if you found a solution for this, but I recently came up against the same issue trying to make a field required on the client-side if and only if another checkbox was checked, and Googling certainly didn't help much...

So, I came up with what I think is a reasonably nice hack to work around it, with a very small modification to the xVal script.

In xVal.jquery.validate.js, find the function _registerCustomValidationFunction. There will be a line that says:

if (this.optional(element))

Change this to be:

if (this.optional(element) && !params.validateEmpty)

Now, when you register your custom rule, just include a boolean parameter called validateEmpty with a value of true, e.g.:

.AddRule("DeliveryNoteNumber", new CustomRule("validateDeliveryNoteNumber", new { validateEmpty = true }, "This field is required."));

That's it! Leaving the parameter out, or setting it to false, leaves xVal to behave as it used to, so it has no ill effect on existing code.

Hopefully someone will find this useful. (And maybe the authors of xVal will impelement something to allow for this :))

Apr 26, 2010 at 12:28 PM

Thanks stile1201.  I found your fix very useful.

Sep 29, 2010 at 6:35 PM

Thanks stile1201!

I wasted about 2 hours trying to figure out why it wasn't firing :(