My forms have inputs with default helper text that guides the user on what to enter (rather than using labels). This makes validation tricky because the input value is never null.
How can I extend unobtrusive validation to handle this? The form shouldn't be valid if the Name input is equal to "Please enter your name..."
I started reading Brad Wilson's blog post on validation adapters, but I'm not sure if this is the right way to go? I need to be able to validate against different default values depending on the field.
Thanks
Yes thats the right way to go. You should implement your own atribute and implement
IClientValidatable
.You could also have a required boolean value set initially to
false
as a hidden form field. When the user changes the textbox, set it to true.Here's a sample illustrating how you could proceed to implement a custom validation attribute:
and then on the model:
controller:
and view:
The ideal solutions is a custom Attribute where you specify minimum and maximum lengths as well as MustNotContain="Please enter your name...".
It took a little while since your question was asked, but if you still like data annotations, this problem can be easily solved using this library:
Above, the field value is compared with some pre-defined text. Alternatively, you can compare fields values with each other:
...and when the case of the strings being compared does not matter:
To improve a little bit of @Darin Dimitrov answer, if you want to add messages from the resources using
ErrorMessageResourceName and ErrorMessageResourceType
, just add this to the to the Error messageErrorMessage = ErrorMessage ?? ErrorMessageString
The ErrorMessageString will look for the localized version of error message that you set in the model using those parameters (ErrorMessageResourceName and ErrorMessageResourceType)
You could make your ViewModel implement IValidatableObject and when implementing the Validate method (from IValidatableObject) add some logic to check the values of the properties e.g.
Now, when Model.IsValid is called in your controller, this bit of logic will be ran and will return validation errors as normal.