1

Trying to get my head around unobtrusive validation. I created a simple page like this:

@using (Html.BeginForm())
{
<text>Validation for name should fail unless this box contains the word christmas</text>
    @Html.TextBoxFor(c => c.IsChristmas, new { id = "IsChristmas" })        <br />
    @Html.TextBoxFor(c => c.Name)

    @Html.ValidationMessageFor(c => c.Name)
    <br />

    <input type="submit" value="Submit" />
}

The model just has two strings, [Required] Name and IsChristmas.

This works fine, if you press submit when the text box is empty, you get the Name is required validation error appearing.

What I want to do now is make a validation error appear when they try to submit, if the first textbox doesn't contain the word 'Christmas'. This is just to learn how I can create my own custom validation types. I don't want to use data attributes, I want to do it entirely in javascript. I'd like to hook into the existing unobtrusive stuff if possible.

Any ideas?

I figured I could write a function first:

function isChristmas()
{
   return $('#isChristmas').val() == 'christmas';
}

Then perhaps I can register it somehow so it is called on submit? Either directly into the validation code, by registering some kind of handler, or write my own handler (a submit button click event) that calls isChristmas() and if it's false, calls a method to display the validation error.

I am not sure how flexible the unobtrusive stuff is. I guess another desirable thing would be that if the page is submitted with the validation being bypassed, I can check server-side as well and have it go back to the view and somehow display the error that way too.

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • See [link](http://stackoverflow.com/a/9247397/4684493) – Hintham Dec 04 '15 at 15:59
  • Why do you not want to do it with validation attributes? That's what they are designed for and means you get both client side and server side validation out of the box (and with less code). You can always add your own rules to `jquery.validation` but then you need to repeat the logic again on the server. And property `IsChristmas` sounds like it should be a `boolean` property in which case you can just use a [foolproof](http://foolproof.codeplex.com/) `[RequiredIfTrue("IsChristmas")]` or similar attribute on your `Name` property. –  Dec 05 '15 at 00:56

0 Answers0