Skip to content

Instantly share code, notes, and snippets.

@ProximaB
Created July 10, 2019 07:06
Show Gist options
  • Save ProximaB/8fc47ad605376bf6a58207951b9f6c3c to your computer and use it in GitHub Desktop.
Save ProximaB/8fc47ad605376bf6a58207951b9f6c3c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ValidatorDekorator
{
class Program
{
static void Main(string[] args)
{
var car = new Car();
car.Brand = "";
car.Model = "Series 5";
car.Version = "F10";
car.Power = 560;
car.GetType()
.GetProperties()
.ToList()
.ForEach(p => System.Console.WriteLine($"{p.Name} = {p.GetValue(car)}"));
Console.WriteLine("Validation!");
car.Validate();
Console.WriteLine("Hello World!");
}
}
public class Car : ValidateGridView
{
[NotEmpty("Brand is required!")] public string Brand { get; set; }
public string Model { get; set; }
[NotEmpty("Version is required!")] public string Version { get; set; }
public int Power { get; set; }
public int Torque { get; set; }
public float Weight { get; set; }
public float Length { get; set; }
}
[System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class NotEmpty : Attribute
{
readonly string _errorDescription;
public NotEmpty(string errorDescription) => _errorDescription = errorDescription;
public string ErrorDescription
{
get { return _errorDescription; }
}
public bool IsValid(object value)
{
if (value == null)
return false;
var stringValue = value as string;
if (stringValue != null)
return stringValue.Trim().Length != 0;
return true;
}
}
public class ValidateGridView
{
public void Validate()
{
var properites = this.GetType().GetProperties();
var attrs = properites.Select(p =>
(property: p, atribute: p.GetCustomAttributes(false).OfType<NotEmpty>()));
List<string> validationresultOutput = new List<string>();
foreach (var attr in attrs)
{
var propValue = attr.property.GetValue(this);
var validationresult =
attr.atribute.Select(a => a.IsValid(propValue) ? string.Empty : a.ErrorDescription);
validationresultOutput.Add(
$"{attr.property.Name}: {string.Join(", ", validationresult.Where(a => !string.IsNullOrEmpty(a)))}");
}
validationresultOutput.ForEach(Console.WriteLine);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment