1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
- using System.Globalization;
- using Bowin.Common.JSON;
- namespace EMIS.ViewModel
- {
- public class TotalLengthAttribute : ValidationAttribute, IClientValidatable
- {
- public int Length { get; set; }
- public IList<string> RelateControls { get; set; }
- public TotalLengthAttribute(int length, params string[] relateControls)
- {
- this.Length = length;
- if (relateControls == null)
- {
- RelateControls = new List<string>();
- }
- else
- {
- RelateControls = relateControls.ToList();
- }
- }
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- string totalString = "";
- List<string> errorMessage = new List<string>();
- foreach (var relateControl in RelateControls)
- {
- var property = validationContext.ObjectType.GetProperty(relateControl);
- if (property == null)
- {
- errorMessage.Add(string.Format(CultureInfo.CurrentCulture, "{0} 不存在", relateControl));
- continue;
- }
- //获取属性的值
- var otherValue = property.GetValue(validationContext.ObjectInstance, null);
- totalString += Convert.ToString(otherValue);
- }
- if (errorMessage.Count > 0)
- {
- return new ValidationResult(string.Join(",", errorMessage));
- }
- if (totalString.Length != this.Length)
- {
- return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
- }
- return null;
- }
- public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
- {
- var rule = new ModelClientValidationRule
- {
- ValidationType = "totallength",
- ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
- };
- rule.ValidationParameters["length"] = Length;
- rule.ValidationParameters["other"] = RelateControls.ToJson();
- yield return rule;
- }
- }
- }
|