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.