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.
Here is my custom validator class:
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<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "stringrequired"
};
yield return rule;
}
}
Here is the view model class property declaration:
[Display(Name = "Custom Property")]
[StringRequired(ErrorMessage="My custom error message goes here")]
public string MyProperty { get; set; }
Here is my script:
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;
},'');
This is my html markup:
<textarea cols="20" data-val="true" data-val-stringrequired="My custom message is
displayed here" id="MyProperty" name="MyProperty" rows="2">
</textarea>
I have ClientValidationEnabled & UnobtrusiveJavaScriptEnabled set to "true" in web.config
For some reason this is not working. Would appreciate help here. Thank you!
//problem is this method is never fired
– AaronLS@Html.TextAreaFor<>
and make sure you are loading references to the jQuery unobtrusive library. – Jay