Skip to content Skip to sidebar Skip to footer

How To Validated Fields In An Xamarin/android App

Does any one know how to make a field required in Xamarin/Android app? I have this field and button in my Android Layout, and I'd like to make sure the info is entered before they

Solution 1:

There are a number of ways to validate input depending upon what your user experience requirements are.

android:digits to restrict input:

<EditText
    android:id="@+id/zipCodeEntry"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="1234567890-"
/>

Validate after entry done and show error message:

button.Click += delegate { 
if (!ValidateZipCode(zipCodeEntry.Text))
{
    zipCodeEntry.Error = "Enter Valid USA Zip Code";
    return;
}
DoSubmit();

protectedboolValidateZipCode(string zipCode)
{
    string pattern = @"^\d{5}(\-\d{4})?$";
    var regex = new Regex(pattern);
    Log.Debug("V", regex.IsMatch(zipCode).ToString());
    return regex.IsMatch(zipCode);
}

enter image description here

Implement View.IOnKeyListener on your Activity and check/validate every key entry

zipCodeEntry.SetFilters(new IInputFilter[] { this });


publicboolOnKey(View view, [GeneratedEnum] Keycode keyCode, KeyEvent e){
    if (view.Id == Resource.Id.zipCodeEntry)
    {
        Log.Debug("V", keyCode.ToString()); // Validate key by key
    }
    returnfalse;
}

Use an InputFilter (Implement IInputFilter on your activity):

public ICharSequence FilterFormatted(ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
    StringBuildersb=newStringBuilder();
    for (inti= start; i < end; i++)
    {
        if ((Character.IsDigit(source.CharAt(i)) || source.CharAt(i) == '-'))
            sb.Append(source.CharAt(i));
    }
    return (sb.Length() == (end - start)) ? null : newJava.Lang.String(sb.ToString());
}

Post a Comment for "How To Validated Fields In An Xamarin/android App"