1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 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; }
- /// <summary>
- ///
- /// </summary>
- /// <param name="length"></param>
- /// <param name="relateControls"></param>
- public TotalLengthAttribute(int length, params string[] relateControls)
- {
- this.Length = length;
- if (relateControls == null)
- {
- RelateControls = new List<string>();
- }
- else
- {
- RelateControls = relateControls.ToList();
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="value"></param>
- /// <param name="validationContext"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="metadata"></param>
- /// <param name="context"></param>
- /// <returns></returns>
- 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;
- }
- }
- }
|