yavsc/Yavsc.Server/Attributes/Validation/YaRequiredAttribute.cs

37 lines
1.1 KiB
C#

7 years ago
using System;
namespace Yavsc.Attributes.Validation
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
7 years ago
public class YaRequiredAttribute : YaValidationAttribute
7 years ago
{
/// <summary>
/// Gets or sets a flag indicating whether the attribute should allow empty strings.
/// </summary>
public bool AllowEmptyStrings { get; set; }
public YaRequiredAttribute (string msg) : base()
{
ErrorMessage = msg;
}
public YaRequiredAttribute ()
{
7 years ago
this.ErrorMessage = ResourcesHelpers.GlobalLocalizer["RequiredField"];
7 years ago
}
public override bool IsValid(object value) {
if (value == null) {
return false;
}
// only check string length if empty strings are not allowed
var stringValue = value as string;
if (stringValue != null && !AllowEmptyStrings) {
return stringValue.Trim().Length != 0;
}
return true;
}
}
7 years ago
7 years ago
}