Here are a couple of questions. Firstly, you are 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.js NOT included. This is because jquery.validate.unobtrusive.js automatically parses and produces a validator for the document, and the very first thing that validate does is to check if the existing validator exists and if it completes.
If you decide to follow an unobtrusive route, be sure to use $.validator.unobtrusive.adapters.add , as this will lead to an error without jquery.validate.unobtrusive.js .
I would recommend you with an unobtrusive test, although I think you are using MVC3. If you are going with unobtrusive validation, you have two options, set the data- * attributes yourself by adding data-val="true" data-val-nohtml="Html not allowed" in your text box, as suggested by JohnnyO, and including a range with data-valmsg-for="note" data-valmsg-replace="true" to show an error message. Or you can create your own DataAnnotation attribute.
Here's the code for addMethod (needed for both types of validation)
<script type="text/javascript"> (function ($) { $.validator.addMethod('nohtml', function (value, element) { // Test 'value' for html here. 'value' is the value of the control being validated. return true; // Return true or false depending on if it passes or fails validation, respectively. }, 'Html not allowed'); } (jQuery)); </script>
and javascript needed for unobtrusive looks like this
$.validator.unobtrusive.adapters.addBool('nohtml');
Regarding how to create a custom validation attribute, since I'm not sure which language you are using if you are using MVC3, or if you need this information for more than 4 months after you asked, I am going to just leave these links for reference.
A brief comparative example of traditional and unobtrusive JavaScript validation in MVC 3 - Mitchell Trent Blog
ASP.NET MVC 3 Custom Validation - Microsoft Developer Network
MHollis Jul 15 '11 at 2:59 a.m. 2011-07-15 02:59
source share