|
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
namespace CustomValidatorDemo
{
[ConfigurationElementType(typeof(MutilValueValidatorData))]
public class MutilValueValidator : Validator<string>
{
private IList<string> _MutilValues;
public IList<string> MutilValues
{
get { return _MutilValues; }
set { _MutilValues = value; }
}
private char _Seperator;
public char Seperator
{
get { return _Seperator; }
set { _Seperator = value; }
}
public MutilValueValidator(IList<string> mutilValues, char seperator)
: this(mutilValues, seperator, null)
{ }
public MutilValueValidator(IList<string> mutilValues, char seperator, string messageTemplate)
: base(messageTemplate, null)
{
if (mutilValues != null)
{
_MutilValues = mutilValues;
_Seperator = seperator;
}
else
{
throw new ArgumentNullException("mutilValues can not be null.");
}
}
internal MutilValueValidator(MutilValueValidatorData configData)
: this(new List<string>(configData.MutilValue.Split(configData.Seperator)), configData.Seperator, configData.MessageTemplate)
{ }
protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
{
if (objectToValidate != null)
{
string[] splitedList = objectToValidate.Split(Seperator);
foreach (string s in splitedList)
{
if (!MutilValues.Contains(s))
{
//驗證錯誤,記錄驗證結果
LogValidationResult(validationResults, GetMessage(objectToValidate, key), currentTarget, key);
return;
}
}
}
}
protected override string DefaultMessageTemplate
{
get { return "{0}: {1}, MutilValueValidator Failed."; }
}
}
}
MutilValueValidator.cs |
|