Files
decePubClient/Components/Daisy/DInputBase.cs
T

45 lines
2.0 KiB
C#
Raw Normal View History

using System.Globalization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
namespace decePubClient.Components.Daisy;
/// <summary>
/// Base of the daisyUI form fields. It is Blazor's <see cref="InputBase{TValue}"/>, so <c>@bind-Value</c> and
/// EditForm validation work as with InputText; it also works outside an EditForm, as long as the value is bound.
/// A consumer's <c>class</c> stays in AdditionalAttributes, and <see cref="InputBase{TValue}.CssClass"/> adds the
/// EditContext's valid/invalid/modified markers to it.
/// </summary>
public abstract class DInputBase<TValue> : InputBase<TValue>
{
/// <summary>Whether the bound field currently has validation messages.</summary>
protected bool IsInvalid => EditContext != null && EditContext.GetValidationMessages(FieldIdentifier).Any();
/// <summary>The attributes for the inner input element, without class (that goes on the styled element).</summary>
protected IReadOnlyDictionary<string, object> InputAttributes =>
AdditionalAttributes?.Where(a => a.Key != "class").ToDictionary(a => a.Key, a => a.Value);
/// <summary>
/// The name attribute, or null so none is rendered. InputBase.NameAttributeValue is "" outside a form that maps
/// field names, which would group every radio and checkbox on the page.
/// </summary>
protected string NameAttribute => string.IsNullOrEmpty(NameAttributeValue) ? null : NameAttributeValue;
protected static string Cx(params string[] classes) => DCx.Join(classes);
protected override string FormatValueAsString(TValue value) =>
BindConverter.FormatValue(value, CultureInfo.InvariantCulture)?.ToString();
protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
{
if (BindConverter.TryConvertTo(value, CultureInfo.InvariantCulture, out result))
{
validationErrorMessage = null;
return true;
}
validationErrorMessage = $"The {DisplayName ?? FieldIdentifier.FieldName} field is not valid.";
return false;
}
}