Files
Multiplechoicetrainer/MultipleChoiceTrainer/Validation/NotEmptyChoiceCollectionAttribute.cs
2020-06-10 13:23:29 +02:00

44 lines
1.1 KiB
C#

using MultipleChoiceTrainer.Models.DataModels;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MultipleChoiceTrainer.Validation
{
public class NotEmptyChoiceCollectionAttribute : ValidationAttribute
{
public NotEmptyChoiceCollectionAttribute()
{
}
public override bool IsValid(object value)
{
ErrorMessage = "Es müssen mindestens zwei Antwortmöglichkeiten eingegeben werden!";
if (value == null || !(value is ICollection<Choice> collection))
{
return false;
}
if(collection == null || collection.Where(e => !string.IsNullOrEmpty(e.Text)).Count() < 2)
{
return false;
}
if(!collection.Where(e => !string.IsNullOrEmpty(e.Text)).Any(e => e.IsTrue))
{
ErrorMessage = "Es muss mindestens eine richtige Antwort eingegeben werden!";
return false;
}
return true;
}
}
}