Restricting input length and characters for Entry field in Xamarin.Forms

Ken K picture Ken K · Aug 1, 2014 · Viewed 40.1k times · Source

How can I restrict the length and characters entered in an Entry control in Xamarin.Forms. Do I need to create a custom control? Is there a way I can derive from Entry (or another control) so I can apply the necessary per-platform input limitations.

An example would be a numeric field that is restricted to a maximum of 3 characters, digits only.

Setting the Keyboard property of an Entry control to Keyboard.Numeric only sets the keyboard for iOS. It does not restrict the actual text entry - i.e. I can still enter non-digit characters. Nor do I see a way to limit the length of entry.

Answer

Femil Shajin picture Femil Shajin · Aug 4, 2014

You can restrict the number of charecters in the Entry field as given below,

  int restrictCount = <your restriction length> //Enter your number of character restriction
  Entry entry = new Entry();
  entry.TextChanged += OnTextChanged;

  void OnTextChanged(object sender, EventArgs e)
  {
    Entry entry = sender as Entry;
    String val = entry.Text; //Get Current Text

    if(val.Length > restrictCount)//If it is more than your character restriction
    {
     val = val.Remove(val.Length - 1);// Remove Last character 
     entry.Text = val; //Set the Old value
    }
  }