'How to automatically move focus to next field after entering a digit?

I'm porting code from Google Sheets to NativeScript.

I have a form with fields where only one digit [1..9] is allowed. In Google Sheets I use menu Data - Data validation to set the rules for the field:

Data validation in Google Sheets

In NativeScript I found these properties for TextField that I have to use: keyboardType, maxLength. So my XML code looks like:

<TextField text="{{ number }}" hint="" maxLength="1" keyboardType="number"/> 

It works ok except two things:

  1. It doesn't show the warning if the user enters an incorrect digit. The "0" is not allowed.
  2. It doesn't move the focus to the next field if the user enters the correct digit (from 1 to 9).

I know that HTML input field has the special property "pattern" where you can "Specifies a regular expression that an element's value is checked against".

How to do similar things in NativeScript? How to move the focus to the next field after the user enters the correct data (digit)?



Solution 1:[1]

For a Nativescript Textfield as mentioned above, you can use an angular validation in the typescript to validate the pattern along with the formcontrol on the html, as given below:

<FlexboxLayout width="100%" [formGroup]="loginForm">
<TextField class="textfield" maxLength="10" keyboardType="number" formControlName = "mobile" hint="{{'enter'|L}} {{'mobile'|L}}"></TextField>
</FlexboxLayout>

Make sure you get the value of the form using the form control in TS by first declaring the form control and then getting the value through the form.

this.loginForm = new FormGroup({
        'mobile':new FormControl(null,[Validators.required,Validators.pattern(Constant.MOBILE_PATTERN_WO_QUOTE)]),
    });

Get the value from the form as :

value = this.loginForm.value.mobile;

You can use the textChange callback function available on the TextField component, to check the validation and length. Once that is done, get the view of the next textfield to focus to by using the page functions.

constructor(
    private page:Page
) {}

onTextChange(args){
    let textfield = args.object as TextField;
    
    if(textfield.text.length==1){
    let nextTextfield = this.page.getViewById('password') as TextField; 
    nextTextfield?.focus(); 
}

If you want to clear the focus, you can use something like this,

textfield.nativeView.clearFocus();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kamil Kafoor