SocialPub/PrivaPub.ClientModels/ValidatorAttributes/NoWhiteSpacesAttribute.cs

61 lines
1.1 KiB
C#
Raw Normal View History

2023-02-19 00:43:43 +01:00
using PrivaPub.ClientModels.Resources;
2023-02-18 08:52:17 +01:00
using System.ComponentModel.DataAnnotations;
2023-02-19 00:43:43 +01:00
namespace PrivaPub.ClientModels.ValidatorAttributes
2023-02-18 08:52:17 +01:00
{
[AttributeUsage(AttributeTargets.Property)]
public class NoWhiteSpacesAttribute : ValidationAttribute
{
const string errorMessageResourceName = "EmptySpacesNotAllowed";
readonly Type errorMessageResourceType = typeof(ErrorsResource);
readonly string[] spaces = new[] {
" ",
" ",
" ",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
" ",
};
public NoWhiteSpacesAttribute()
{
ErrorMessageResourceName = errorMessageResourceName;
ErrorMessageResourceType = errorMessageResourceType;
}
public override bool IsValid(object value)
{
var str = value?.ToString();
if (string.IsNullOrEmpty(str))
return true;
var hasWhiteSpace = false;
try
{
foreach (var space in spaces)
{
hasWhiteSpace = str.Contains(space);
if (hasWhiteSpace) break;
}
return !hasWhiteSpace;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
}