本文整理汇总了C#中System.ComponentModel.DataAnnotations.ValidationResult类的典型用法代码示例。如果您正苦于以下问题:C# ValidationResult类的具体用法?C# ValidationResult怎么用?C# ValidationResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ValidationResult类属于System.ComponentModel.DataAnnotations命名空间,在下文中一共展示了ValidationResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ValueComparisonAttribute
/// <summary>
/// Initializes new instance of the <see cref="ValueComparisonAttribute"/> class.
/// </summary>
/// <param name="otherProperty">The name of the other property.</param>
/// <param name="comparison">The <see cref="ValueComparison"/> to perform between values.</param>
public ValueComparisonAttribute(string propertyName, ValueComparison comparison)
: base(propertyName)
{
this.comparison = comparison;
this.failure = new ValidationResult(String.Empty);
this.success = ValidationResult.Success;
}
示例2: IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
if (otherPropertyInfo.PropertyType.Equals(new TimeSpan().GetType()))
{
var toValidate = (TimeSpan)value;
var referenceProperty = (TimeSpan)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (toValidate.CompareTo(referenceProperty) < 1)
{
validationResult = new ValidationResult(ErrorMessageString);
}
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
throw ex;
}
return validationResult;
}
示例3: IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
var sum = (double)value;
var creditId = (int)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
using (var scope = CustomDependencyResolver.Resolver.BeginScope())
{
var creditService = scope.GetService(typeof (ICreditService)) as ICreditService;
if (creditService == null)
{
validationResult = new ValidationResult("Cannot resolve ICreditService");
}
else
{
var credit = creditService.Get(creditId);
if (sum < credit.MinSum || sum > credit.MaxSum)
{
var errorMessage = String.Format("Sum should be between {0} and {1}.", credit.MinSum,
credit.MaxSum);
validationResult = new ValidationResult(errorMessage);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return validationResult;
}
示例4: Constructor_String_IEnumerable
public void Constructor_String_IEnumerable ()
{
var vr = new ValidationResult ("message", null);
Assert.AreEqual ("message", vr.ErrorMessage, "#A1");
Assert.IsNotNull (vr.MemberNames, "#A2-1");
int count = 0;
foreach (string m in vr.MemberNames)
count++;
Assert.AreEqual (0, count, "#A2-2");
var names = new string[] { "one", "two" };
vr = new ValidationResult ("message", names);
Assert.AreEqual ("message", vr.ErrorMessage, "#A1");
Assert.IsNotNull (vr.MemberNames, "#A2-1");
Assert.AreSame (names, vr.MemberNames, "#A2-2");
count = 0;
foreach (string m in vr.MemberNames)
count++;
Assert.AreEqual (2, count, "#A2-3");
vr = new ValidationResult (null, null);
Assert.AreEqual (null, vr.ErrorMessage, "#A3");
}
示例5: IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var errorMessage = $"The {validationContext.DisplayName} field is required.";
var validationResult = new ValidationResult(errorMessage, new string[] { validationContext.DisplayName });
if (value == null) return validationResult;
if (value is string && string.IsNullOrWhiteSpace(value.ToString()))
{
return validationResult;
}
var incoming = value.ToString();
decimal val = 0;
if (Decimal.TryParse(incoming, out val) && val == 0)
{
return validationResult;
}
var date = DateTime.MinValue;
if (DateTime.TryParse(incoming, out date) && date == DateTime.MinValue)
{
return validationResult;
}
return ValidationResult.Success;
}
示例6: Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var failedValidationResult = new ValidationResult("An error occured!");
var failedResult = new[] { failedValidationResult };
if (!string.IsNullOrEmpty(this.Honeypot))
{
return failedResult;
}
DateTime timestamp;
if (!DateTime.TryParseExact(this.Timestamp, "ffffMMHHyytssmmdd",
null, DateTimeStyles.None, out timestamp))
{
return failedResult;
}
if (DateTime.Now.AddMinutes(-5) > timestamp)
{
return failedResult;
}
return new[] { ValidationResult.Success };
}
示例7: Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResults = new HashSet<ValidationResult>();
var contest = this.data.Contests.GetById(this.ContestId);
var contestQuestions = contest.Questions
.Where(x => !x.IsDeleted)
.ToList();
var counter = 0;
foreach (var question in contestQuestions)
{
var answer = this.Questions.FirstOrDefault(x => x.QuestionId == question.Id);
var memberName = string.Format("Questions[{0}].Answer", counter);
if (answer == null)
{
var validationErrorMessage = string.Format(Resource.Question_not_answered, question.Id);
var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
validationResults.Add(validationResult);
}
else if (!string.IsNullOrWhiteSpace(question.RegularExpressionValidation) && !Regex.IsMatch(answer.Answer, question.RegularExpressionValidation))
{
var validationErrorMessage = string.Format(Resource.Question_not_answered_correctly, question.Id);
var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
validationResults.Add(validationResult);
}
counter++;
}
return validationResults;
}
示例8: IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = new ValidationResult("\"" + value.ToString() + "\"" + ErrorMessageString);
try
{
if (value is string)
{
string frequencyString = (string)value;
if (frequencyString.Equals("hourly"))
validationResult = ValidationResult.Success;
if (frequencyString.Equals("daily"))
validationResult = ValidationResult.Success;
if (frequencyString.Equals("weekly"))
validationResult = ValidationResult.Success;
if (frequencyString.Equals("monthly"))
validationResult = ValidationResult.Success;
if (frequencyString.Equals("yearly"))
validationResult = ValidationResult.Success;
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type String");
}
}
catch (Exception ex)
{
// Do stuff, i.e. log the exception
// Let it go through the upper levels, something bad happened
throw ex;
}
return validationResult;
}
示例9: Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResults = new HashSet<ValidationResult>();
var contest = this.regData.CustomerCards.GetById(this.ContestId);
var contestQuestions = contest.Questions.ToList();
var counter = 0;
foreach (var question in contestQuestions)
{
var answer = this.Questions.FirstOrDefault(x => x.QuestionId == question.Id);
var memberName = string.Format("Questions[{0}].Answer", counter);
if (answer == null)
{
var validationErrorMessage = string.Format("Question with id {0} was not answered.", question.Id);
var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
validationResults.Add(validationResult);
}
else if (!string.IsNullOrWhiteSpace(question.RegularExpressionValidation) &&
!Regex.IsMatch(answer.Answer, question.RegularExpressionValidation))
{
var validationErrorMessage = string.Format(
"Question with id {0} is not in the correct format.", question.Id);
var validationResult = new ValidationResult(validationErrorMessage, new[] { memberName });
validationResults.Add(validationResult);
}
counter++;
}
return validationResults;
}
示例10: IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
string pw = value.ToString();
bool num = false;
bool letter = false;
foreach (char c in pw)
{
if (Char.IsDigit(c))
{
num = true;
}
else
{
if (Char.IsLetter(c))
{
letter = true;
}
}
}
if (!num || !letter)
{
validationResult = new ValidationResult(ErrorMessageString);
}
return validationResult;
}
示例11: Can_construct_get_and_set_ErrorMessage
public static void Can_construct_get_and_set_ErrorMessage()
{
var validationResult = new ValidationResult("SomeErrorMessage");
Assert.Equal("SomeErrorMessage", validationResult.ErrorMessage);
validationResult.ErrorMessage = "SomeOtherErrorMessage";
Assert.Equal("SomeOtherErrorMessage", validationResult.ErrorMessage);
}
示例12: IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
// Using reflection we can get a reference to the other date property, in this example the project start date
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
// Let's check that otherProperty is of type DateTime as we expect it to be
if (otherPropertyInfo.PropertyType.Equals(new DateTime().GetType()))
{
DateTime toValidate = (DateTime)value;
DateTime referenceProperty = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
// if the end date is lower than the start date, than the validationResult will be set to false and return
// a properly formatted error message
if (toValidate.CompareTo(referenceProperty) < 1)
{
//string message = FormatErrorMessage(validationContext.DisplayName);
//validationResult = new ValidationResult(message);
validationResult = new ValidationResult(ErrorMessageString);
}
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
// Do stuff, i.e. log the exception
// Let it go through the upper levels, something bad happened
throw ex;
}
return validationResult;
}
示例13: ValidateAttributes
private static IEnumerable<ValidationResult> ValidateAttributes(object instance,
ValidationContext validationContext,
string prefix)
{
PropertyDescriptor[] propertyDescriptorCollection =
TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>().ToArray();
IEnumerable<ValidationResult> valResults = propertyDescriptorCollection.SelectMany(
prop => prop.Attributes.OfType<ValidationAttribute>(), (prop, attribute) =>
{
validationContext.DisplayName = prop.Name;
ValidationResult validationresult = attribute.GetValidationResult(prop.GetValue(instance),
validationContext);
if (validationresult != null)
{
IEnumerable<string> memberNames = validationresult.MemberNames.Any()
? validationresult.MemberNames.Select(c => prefix + c)
: new[] { prefix + prop.Name };
validationresult = new ValidationResult(validationresult.ErrorMessage, memberNames);
}
return validationresult;
})
.Where(
validationResult =>
validationResult !=
ValidationResult.Success);
return
valResults;
}
示例14: ValidationResult
/// <summary>
/// Constructor that creates a copy of an existing ValidationResult.
/// </summary>
/// <param name="validationResult">The validation result.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="validationResult"/> is null.</exception>
protected ValidationResult(ValidationResult validationResult) {
if (validationResult == null) {
throw new ArgumentNullException("validationResult");
}
this._errorMessage = validationResult._errorMessage;
this._memberNames = validationResult._memberNames;
}
示例15: ValidationResult
/// <summary>
/// Initializes a new instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class by
/// using a <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> object.
/// </summary>
/// <param name="validationResult">The validation result object.</param>
protected ValidationResult( ValidationResult validationResult )
{
if ( validationResult == null )
throw new ArgumentNullException( "validationResult" );
ErrorMessage = validationResult.ErrorMessage;
memberNames = validationResult.memberNames;
}