This is the universal way how to do this:
private string GenerateValidationModel<T>()
{
var name = typeof(T).Name.Replace("Model", "ViewModel");
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
var validationModel = "var " + name + " = {
";
foreach (var prop in typeof(T).GetProperties())
{
object[] attrs = prop.GetCustomAttributes(true);
if (attrs == null || attrs.Length == 0)
continue;
string conds = "";
foreach (Attribute attr in attrs)
{
if (attr is MinLengthAttribute)
{
conds += ", minLength: " + (attr as MinLengthAttribute).Length;
}
else if (attr is RequiredAttribute)
{
conds += ", required: true";
}
// ...
}
if (conds.Length > 0)
validationModel += String.Format("{0}: ko.observable().extend({{ {1} }}),
", prop.Name, conds.Trim(',', ' '));
}
return validationModel + "};";
}
Usage:
string validationModel = GenerateValidationModel<LoginModel>();
Output:
var loginViewModel = {
UserName: ko.observable().extend({ minLength: 3, required: true}),
Password: ko.observable().extend({ required: true}),
};
It's good idea to cache the output
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…