Skip to content

Instantly share code, notes, and snippets.

@Redouane64
Created September 13, 2020 13:50
Show Gist options
  • Select an option

  • Save Redouane64/4c4e6ecbd3bfe8781ff59ffaa201773a to your computer and use it in GitHub Desktop.

Select an option

Save Redouane64/4c4e6ecbd3bfe8781ff59ffaa201773a to your computer and use it in GitHub Desktop.
Validate POCOs in .NET - Examples
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Xunit;
using Xunit.Abstractions;
namespace DataAnnotationsAndValidation
{
public class ValidationTests
{
class MyPoco
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
private readonly ITestOutputHelper output;
public ValidationTests(ITestOutputHelper outputHelper)
{
this.output = outputHelper;
}
[Fact]
public void RequireEmailAddress()
{
var poco = new MyPoco();
var vc = new ValidationContext(poco);
var result = new List<ValidationResult>();
var r = Validator.TryValidateObject(poco, vc, result);
Assert.False(r);
}
[Fact]
public void IsNotAValidEmailAddress()
{
var poco = new MyPoco() {
Email = "this is not a valid e-mail address lol!"
};
var vc = new ValidationContext(poco) { MemberName = nameof(MyPoco.Email) };
var result = new List<ValidationResult>();
var r = Validator.TryValidateProperty(poco.Email, vc, result);
output.WriteLine(result[0].ErrorMessage);
Assert.False(r);
}
[MaxLength(8)]
[RegularExpression("[0-9]*", ErrorMessage = "Only digits are allowed.")]
public string Value { get; } = "12345678";
[Fact]
public void IsEightNumbersOnly()
{
var vc = new ValidationContext(this) { MemberName = nameof(ValidationTests.Value) };
var result = new List<ValidationResult>();
var r = Validator.TryValidateProperty(this.Value, vc, result);
Assert.True(r);
}
class Account
{
const int ACCOUNT_NUMBER_MAX_LENGTH = 8;
[MaxLength(ACCOUNT_NUMBER_MAX_LENGTH)]
[RegularExpression("[0-9A-Z]*")]
public string AccountNumber { get; }
public Account()
{
AccountNumber = Guid.NewGuid().ToString().Split('-')[0].ToUpper();
}
}
[Fact]
public void IsValidAccountNumber()
{
var acc = new Account();
var vc = new ValidationContext(acc) { MemberName = nameof(Account.AccountNumber) };
var result = new List<ValidationResult>();
var r = Validator.TryValidateProperty(acc.AccountNumber, vc, result);
Assert.True(r);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment