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.

2
  • See link Commented Dec 4, 2015 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 [RequiredIfTrue("IsChristmas")] or similar attribute on your Name property. Commented Dec 5, 2015 at 0:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.