Skip to content

Instantly share code, notes, and snippets.

@fxcosta
Last active November 13, 2023 16:19
Show Gist options
  • Save fxcosta/d9d4290909880ce5fb7d395d7b90db3f to your computer and use it in GitHub Desktop.
Save fxcosta/d9d4290909880ce5fb7d395d7b90db3f to your computer and use it in GitHub Desktop.
Simple initial input date mask for unity inputfield eg 12/12/1995. PS: working but regex is not completly correct. PS2: Limit input char number on InputField on Inspector
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
using System.Text.RegularExpressions;
public class DateInputMask : MonoBehaviour
{
public UnityEngine.UI.InputField inputField;
private void Awake()
{
inputField.onValueChanged.AddListener(delegate { OnValueChanged(); });
}
public void OnValueChanged()
{
if (string.IsNullOrEmpty(inputField.text))
{
inputField.text = string.Empty;
}
else
{
string input = inputField.text;
string MatchPattern = @"^((\d{2}/){0,2}(\d{1,2})?)$";
string ReplacementPattern = "$1/$3";
string ToReplacePattern = @"((\.?\d{2})+)(\d)";
input = Regex.Replace(input, ToReplacePattern, ReplacementPattern);
Match result = Regex.Match(input, MatchPattern);
if (result.Success)
{
inputField.text = input;
inputField.caretPosition++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment