Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC3 Custom String Client Validation not working
    text
    copied!<p>Newbie to MVC3 and jquery unobtrusive validation. I am trying to achieve a very simple custom string validation for my mvc view model property. I know there is an existing "Required" attribute but wanted to play with my custom for testing purpose.</p> <p>Here is my custom validator class:</p> <pre><code>public class StringRequiredAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { string valueToValidate = value.ToString(); if ((value == null ) || (valueToValidate.IsEmpty())) { return false; } return true; } public override string FormatErrorMessage(string name) { return "formatting my custom message here..."; } public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "stringrequired" }; yield return rule; } } </code></pre> <p>Here is the view model class property declaration:</p> <pre><code>[Display(Name = "Custom Property")] [StringRequired(ErrorMessage="My custom error message goes here")] public string MyProperty { get; set; } </code></pre> <p>Here is my script:</p> <pre><code>jQuery.validator.unobtrusive.adapters.add('stringrequired', [], function (options) { options.rules['stringrequired'] = true; options.messages['stringrequired'] = options.message; } ); jQuery.validator.addMethod('stringrequired', function (value, element, params) { //problem is this method is never fired if (value == undefined || value == null) return false; if (value.toString().length == 0) return false; return true; },''); </code></pre> <p>This is my html markup:</p> <pre><code>&lt;textarea cols="20" data-val="true" data-val-stringrequired="My custom message is displayed here" id="MyProperty" name="MyProperty" rows="2"&gt; &lt;/textarea&gt; </code></pre> <p>I have ClientValidationEnabled &amp; UnobtrusiveJavaScriptEnabled set to "true" in web.config</p> <p>For some reason this is not working. Would appreciate help here. Thank you!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload