What I need:
A mask that works on the keypress
event of a TextBox
replacing non-numeric and excessive hyphens with ""
.
What is my difficulty:
Check for the entry of only one hyphen in the same expression.
I got into the solution using substring and only worked on KeyUP
, but I wanted to get through an expression.
What I've already tried:
using System.Text.RegularExpressions;
private static Regex digitsOnly = new Regex(@"(:?[^\d\-])");
private void inputSequencial_KeyUp(object sender, KeyEventArgs e)
{
if (!String.IsNullOrEmpty(inputSequencial.Text)
{
inputSequencial.Text = digitsOnly.Replace(inputSequencial.Text, "");
//MatchCollection matches = Regex.Matches(inputSequencial.Text, "[\-]");
//
//if (matches.Count > 1)
//{
// for (int i = 1; i <= matches.Count - 1; i++)
// {
// inputSequencial.Text = inputSequencial.Text.Substring(0, matches[i].Index-1) + inputSequencial.Text.Substring(matches[i].Index, inputSequencial.Text.Length);
// inputSequencial.Text = inputSequencial.Text.Replace(inputSequencial.Text[matches[i].Index].ToString(), "");
// }
//}
}
}
Expected result:
If you know better ways to do this please let me know. Thank you for your attention.