SessionZero.SzfToolkit-Dotnet/SessionZero.SzfLib/Parser/SzfField.cs

79 lines
2.7 KiB
C#

using SessionZero.SzfLib.Helpers;
namespace SessionZero.SzfLib.Parser;
public class SzfField(string name, SzfFieldType type)
{
public string Name { get; set; } = name;
public SzfFieldType SzfType { get; set; } = type;
public string? Value { get; set; }
/// <summary>
/// Validates the field based on its type and value. Returns an SzfError object containing validation results, if any.
/// </summary>
/// <param name="canHaveEmptyValue"></param>
/// <returns></returns>
public SzfError Validate(bool canHaveEmptyValue = false)
{
SzfError result = new();
if (string.IsNullOrEmpty(Name))
{
result.AddError("Field name cannot be null or empty.");
}
if (!canHaveEmptyValue && string.IsNullOrEmpty(Value))
{
result.AddError($"Field '{Name}' cannot be empty.");
}
else
{
var isValid = ValidateSzfType(this);
if (!isValid)
{
result.AddError($"Field '{Name}' has an invalid value for type '{SzfType}'.");
}
}
return result;
}
/// <summary>
/// Validates the value of the field based on its SzfType.
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
private bool ValidateSzfType(SzfField field)
{
var modifiedValue = field.Value?.Trim().ToLower();
switch (field.SzfType)
{
case SzfFieldType.Text:
return !string.IsNullOrEmpty(modifiedValue);
case SzfFieldType.TextField:
return !string.IsNullOrEmpty(modifiedValue);
case SzfFieldType.Number:
if (decimal.TryParse(modifiedValue, out _)) return true;
break;
case SzfFieldType.Bool:
if (bool.TryParse(modifiedValue, out _)) return true;
break;
case SzfFieldType.Calculated:
// TODO: Implement validation for calculated fields
// For now, we assume they are valid if they are not empty
return !string.IsNullOrEmpty(modifiedValue);
case SzfFieldType.EntryReference:
// Currently, we assume entry references are valid if they are not empty
return !string.IsNullOrEmpty(modifiedValue);
case SzfFieldType.EntryReferenceList:
// Currently, we assume entry reference lists are valid if they are not empty
return !string.IsNullOrEmpty(modifiedValue);
case SzfFieldType.System:
// System fields are typically predefined and may not require validation
return true;
}
return false;
}
}