i try to add this line ModelState.AddModelError(string key, string errorMessage);
in IsValid
function of ValidationAttribute
class but fail.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class AtleastOneAttribute : ValidationAttribute, IClientValidatable
{
// For Server side
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var oHobby=value as IEnumerable;
foreach (var _object in oHobby)
{
Hobby _oHobby = (Hobby)_object;
if (_oHobby.IsSelected)
{
return ValidationResult.Success;
}
}
}
ModelState.AddModelError("Hobbies", "Err message....");
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
tell me how to access ModelState.AddModelError
from IsValid
function of ValidationAttribute class ?
thanks
ModelState
is not accessible in IsValid
function. IsValid
method adds an error to ModelState
through it's return statement, so if you need to add an error just return it:
return new ValidationResult("Err message....");