I’m trying to write a custom validation that gives an error if html exists in the textarea when they submit a form.
I have the following –
its not working and I’m not sure why.
also I don’t understand the unobtrusive part
can someone show me how to do that as I am seeing other examples on SO that have it.
text area has a class”note”
the form is called “noteform”
<script type="text/javascript" >
$(document).ready(function () {
$.validator.addMethod('nohtml', function (value, element) {
var text = $(".note").text();
if ($(text).length > 0) {
return false;
}
else {
return true;
}
}, 'Html not allowed');
// // **not sure what to do here**
// $.validator.unobtrusive.adapters.add('containsnohtml', {}, function (options) {
// options.rules['nohtml'] = false;
// options.messages['nohtml'] = options.message;
// });
$('#noteform').validate({
rules: { nohtml: "required nohtml" }
});
});
</script>
There’s a couple issues here. One is you’re trying to mix unobtrusive and regular jquery validation. If you want to use validate like this then you need to make sure
jquery.validate.unobtrusive.jsis NOT included. This is becausejquery.validate.unobtrusive.jsautomatically parses and produces a validator for the document and the very first thing thatvalidatedoes is check if there’s an existing validator and exits if there is.If you do decide to go the non-unobtrusive route, be sure not to use the
$.validator.unobtrusive.adapters.addsince it will cause an error withoutjquery.validate.unobtrusive.js.I would recommend going with unobtrusive validation though since I think you’re using MVC3.
If you’re going to go with unobtrusive validation you have two choices, set the data-* attributes yourself by adding
data-val="true" data-val-nohtml="Html not allowed"to your textarea as suggested by JohnnyO and including a span withdata-valmsg-for="note" data-valmsg-replace="true"to show the error message. Or you can make your own DataAnnotation attribute.Here’s the code for the addMethod (needed for both kinds of validation)
and the javascript needed for the unobtrusive is as follows
Regarding how to make a custom validation attribute, since I’m not sure what language you’re using, assuming you’re using MVC3, or if you even need this info anymore 4 months after you asked, I’m going to simply leave these links for reference.
A brief comparision of Traditional vs Unobtrusive JavaScript Validation in MVC 3 – Mitchell Trent’s Blog
ASP.NET MVC 3 Custom Validation – Microsoft Developer Network