Net.Like.Xue.Tokyo/Assets/BITKit/Unity/Scripts/UX/Library/CustomTextField.cs

46 lines
1.2 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
namespace BITKit.UX
{
public class CustomTextField : TextField
{
public const string errorUssName = "error";
public new class UxmlTraits : TextField.UxmlTraits
{
private readonly UxmlStringAttributeDescription m_RegexAttribute = new ()
{
name = "Regex"
};
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var textField = (CustomTextField)ve;
textField.Regex = m_RegexAttribute.GetValueFromBag(bag, cc);
}
}
public new class UxmlFactory : UxmlFactory<CustomTextField, UxmlTraits> { }
public CustomTextField():base()
{
this.RegisterValueChangedCallback(OnValueChangedInternal);
}
public string Regex { get; set; }
public event Action<string> OnValueChanged;
private void OnValueChangedInternal(ChangeEvent<string> evt)
{
var isMatch = string.IsNullOrEmpty(Regex) || System.Text.RegularExpressions.Regex.IsMatch(evt.newValue, Regex);
this.Q("unity-text-input").EnableInClassList(errorUssName, !isMatch);
if (isMatch)
{
OnValueChanged?.Invoke(evt.newValue);
}
}
}
}