TMP_PhoneNumberValidator.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. namespace TMPro
  5. {
  6. /// <summary>
  7. /// Example of a Custom Character Input Validator to only allow phone number in the (800) 555-1212 format.
  8. /// </summary>
  9. [Serializable]
  10. //[CreateAssetMenu(fileName = "InputValidator - Phone Numbers.asset", menuName = "TextMeshPro/Input Validators/Phone Numbers")]
  11. public class TMP_PhoneNumberValidator : TMP_InputValidator
  12. {
  13. // Custom text input validation function
  14. public override char Validate(ref string text, ref int pos, char ch)
  15. {
  16. Debug.Log("Trying to validate...");
  17. // Return unless the character is a valid digit
  18. if (ch < '0' && ch > '9') return (char)0;
  19. int length = text.Length;
  20. // Enforce Phone Number format for every character input.
  21. for (int i = 0; i < length + 1; i++)
  22. {
  23. switch (i)
  24. {
  25. case 0:
  26. if (i == length)
  27. text = "(" + ch;
  28. pos = 2;
  29. break;
  30. case 1:
  31. if (i == length)
  32. text += ch;
  33. pos = 2;
  34. break;
  35. case 2:
  36. if (i == length)
  37. text += ch;
  38. pos = 3;
  39. break;
  40. case 3:
  41. if (i == length)
  42. text += ch + ") ";
  43. pos = 6;
  44. break;
  45. case 4:
  46. if (i == length)
  47. text += ") " + ch;
  48. pos = 7;
  49. break;
  50. case 5:
  51. if (i == length)
  52. text += " " + ch;
  53. pos = 7;
  54. break;
  55. case 6:
  56. if (i == length)
  57. text += ch;
  58. pos = 7;
  59. break;
  60. case 7:
  61. if (i == length)
  62. text += ch;
  63. pos = 8;
  64. break;
  65. case 8:
  66. if (i == length)
  67. text += ch + "-";
  68. pos = 10;
  69. break;
  70. case 9:
  71. if (i == length)
  72. text += "-" + ch;
  73. pos = 11;
  74. break;
  75. case 10:
  76. if (i == length)
  77. text += ch;
  78. pos = 11;
  79. break;
  80. case 11:
  81. if (i == length)
  82. text += ch;
  83. pos = 12;
  84. break;
  85. case 12:
  86. if (i == length)
  87. text += ch;
  88. pos = 13;
  89. break;
  90. case 13:
  91. if (i == length)
  92. text += ch;
  93. pos = 14;
  94. break;
  95. }
  96. }
  97. return ch;
  98. }
  99. }
  100. }