4

I have TextField using Angular nativescript.

<TextField   (textChange)="onTextChange($event)" ></TextField>

I want to allow only the "a" character to be inserted into that TextField.
All other characters ( "b","c",....) should be prevented - meaning - prevented from inserted.

I already know that I can use the (textChange) event and then delete the char - but that's a too late event.

Question:

Assuming I have a textfield , How can I cross-platform prevent certain chars from being entered ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

3

For Android, you can do it by explicitly setting the allowed instances for setKeyListener of android.widget.Edittext (which is the native Android control behind TextField in NativeScript)

Foor example

export function onTfLoaded(args) {
    let tf = <TextField>args.object;

    let nativeTF;

    if (isAndroid) {
        let nativeTF = <android.widget.EditText>tf.nativeView; // on Android is android.widget.EditText
        nativeTF.setKeyListener(android.text.method.DigitsKeyListener.getInstance("zxc"));
    } else {
        let nativeTF = <UITextField>tf.nativeView;// for iOS is UITextField
    }

}

The above is will allow the user to input only ZXC (works the same as setting digits), however, the solution will still prompt a numeric keyboard.

Nick Iliev
  • 9,610
  • 3
  • 35
  • 89
  • Thanks Nick. I wish NS would have `(onKeyDown)` where it will have `e` to `e.cancel`.... – Royi Namir Feb 14 '18 at 13:41
  • you can directly access the native controls (EditText and UITextField) and use the provided event - e.g. `beforeTextChange` event on `EditText` like done here https://github.com/telerik/nativescript-ui-feedback/issues/339#issuecomment-336791993 .. for iOS I am not sure if there is similar event but if so you can overwrite the delegate method and use it – Nick Iliev Feb 14 '18 at 13:56
  • I lost some time on this because I didn't know keyboardType will mess with this. For example I was adding ',' as one of the digits, but wasn't being accepted because I had keyboard="number" – Felipe Centeno Aug 11 '21 at 00:08