我使用ListValidation
public class Test
{
[ListValidation(ErrorMessage ="wrong")]
public List<string> Listt { get; set; }
}
ListValidation实现
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class ListValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count > 0;
}
return false;
}
}
当我测试时
Test t = new Test();
List<string> str = new List<string>();
str.Add("haha");
str.Add("hoho");
t.Listt = str;
JsonResult json = ModelValidation.ValidateProperty(t, nameof(t.Listt));
抛出ArgumentException
{System.ArgumentException: The value for property 'Listt' must be of type 'System.Collections.Generic.List`1[System.String]'.
Parameter name: value
at System.ComponentModel.DataAnnotations.Validator.EnsureValidPropertyType(String propertyName, Type propertyType, Object value)
at System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(Object value, ValidationContext validationContext, ICollection`1 validationResults)
at EArchive.Infrastructure.ModelValidation.ValidateProperty(Object obj, String property) in C:\Users\haha\ModelValidation.cs:line 54}
ValidateProperty实现
public static JsonResult ValidateProperty(object obj, string property)
{
ValidationContext context = new ValidationContext(obj)
{
MemberName = property
};
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateProperty(property, context, results);
if (!valid) // there is no error and everything is good
{
return null;
}
string errors = "";
// fetch all errors happened in the property.
foreach (ValidationResult result in results)
{
errors += result.ErrorMessage + "\n <br>";
}
Dictionary<string, string> err = new Dictionary<string, string>()
{
{ "status", "fail" },
{ "message", errors }
};
return new JsonResult(err);
}
这里有什么问题?
答案 0 :(得分:1)
<!-- After Form Submitted Validation-->
$("#button").click(function(event){
// prevent the form from being submitted
event.preventDefault();
var form_data=$(".myform").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_"+form_data[input]['name']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
else{error_element.removeClass("error_show").addClass("error");}
}
if (error_free) {
alert('No errors: Form will be submitted');
// submit the form if no errors
$( ".myform" ).submit();
}
else{
alert('Errors shown');
}
});
});
期望第一个参数(Validator.TryValidateProperty
)是要测试属性的值而不是它的名称。在您的示例中,您传递的是字符串object value
,而不是 Listt
的值。为了使其适用于您的目的,您需要更改t.Listt
功能,如下所示:
ValidateProperty
然后,只需相应更新您的呼叫网站:
public static JsonResult ValidateProperty(object propertyValue, string propertyName, object sourceObject)
{
ValidationContext context = new ValidationContext(sourceObject)
{
MemberName = propertyName
};
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateProperty(propertyValue, context, results);
// ...
以下是我用作此答案灵感的博文:https://gigi.nullneuron.net/gigilabs/simple-validation-with-data-annotations/。