113 lines
3.1 KiB
C#
113 lines
3.1 KiB
C#
using UnityEngine;
|
|
using System.Collections;
|
|
|
|
namespace UnityEngine.UI
|
|
{
|
|
public class InputFieldLimit : MonoBehaviour
|
|
{
|
|
public int lengthLimit = 10;
|
|
public int wordType = 0; //0字符不受限制 1数字 2字母 4下划线 8所有ascii字符 16汉字 32字符显示*
|
|
|
|
public void SetValue(string value)
|
|
{
|
|
if (m_input == null)
|
|
{
|
|
m_input = GetComponent<InputField>();
|
|
}
|
|
if (m_input == null)
|
|
return;
|
|
|
|
string newRealValue = "";
|
|
string text = "";
|
|
for(int i=0;i<value.Length && i< lengthLimit; i++)
|
|
{
|
|
if(InputValid(value[i])==(char)0)
|
|
{
|
|
m_input.text = "";
|
|
return;
|
|
}
|
|
if ((wordType & 32) != 0)
|
|
{
|
|
newRealValue += value[i];
|
|
//text += '*';
|
|
}
|
|
else
|
|
text += value[i];
|
|
}
|
|
m_input.text = text;
|
|
}
|
|
|
|
InputField m_input;
|
|
void Awake()
|
|
{
|
|
m_input = GetComponent<InputField>();
|
|
if (m_input == null)
|
|
return;
|
|
m_input.onValidateInput = ValidateInput;
|
|
if((wordType & 32) != 0)
|
|
{
|
|
m_input.contentType = InputField.ContentType.Password;
|
|
}
|
|
}
|
|
|
|
private char InputValid(char charInput)
|
|
{
|
|
char returnChar = (char)0;
|
|
int asciiType = (int)charInput;
|
|
if (wordType == 0 || wordType == 32)
|
|
returnChar = charInput;
|
|
|
|
if(wordType == 0)
|
|
{
|
|
returnChar = charInput;
|
|
}
|
|
|
|
if ((wordType & 1) != 0 && asciiType >= 48 && asciiType <= 57)
|
|
{
|
|
returnChar = charInput;
|
|
}
|
|
|
|
if ((wordType & 2) != 0 && ((asciiType >= 65 && asciiType <= 90) || (asciiType >= 97 && asciiType <= 122)))
|
|
{
|
|
returnChar = charInput;
|
|
}
|
|
|
|
if ((wordType & 4) != 0 && asciiType == 95)
|
|
{
|
|
returnChar = charInput;
|
|
}
|
|
|
|
if ((wordType & 8) != 0 && asciiType <= 127)
|
|
{
|
|
returnChar = charInput;
|
|
}
|
|
|
|
if ((wordType & 16) != 0 && asciiType > 127)
|
|
{
|
|
returnChar = charInput;
|
|
}
|
|
return returnChar;
|
|
}
|
|
|
|
char ValidateInput(string text, int charIndex, char addedChar)
|
|
{
|
|
if (m_input == null)
|
|
return (char)0;
|
|
int len = 0;
|
|
string newText = text + addedChar;
|
|
for(int i=0;i<newText.Length;i++)
|
|
{
|
|
len += (((int)newText[i]) > 127 ? 2 : 1);
|
|
}
|
|
if (len > lengthLimit)
|
|
return (char)0;
|
|
char returnChar = InputValid(addedChar);
|
|
if (returnChar == (char)0)
|
|
return returnChar;
|
|
|
|
return returnChar;
|
|
}
|
|
}
|
|
}
|
|
|