Validation of Nativescript empty fields

Asked

Viewed 30 times

0

Need to validate multiple Fields (text, Dropdown) in one form, which is divided into two :

<StackLayout>
    <TextField required [text]="usr.nome" [(ngModel)]="usr.nome"></TextField>
    <TextField required [text]="usr.idade" [(ngModel)]="usr.idade"></TextField>
    <TextField required [text]="usr.endereco" [(ngModel)]="usr.endereco"></TextField>
    <DropDown [items]="itemsList" hint="Escolha" [(ngModel)]="usr.escolaridade" required></DropDown>
</StackLayout>
<StackLayout>
    <TextField required [text]="usr.nome" [(ngModel)]="usr.nome"></TextField>
    <TextField required [text]="usr.idade" [(ngModel)]="usr.idade"></TextField>
    <TextField required [text]="usr.endereco" [(ngModel)]="usr.endereco"> 
    </TextField>
    <DropDown [items]="itemsList" hint="Escolha" [(ngModel)]="usr.escolaridade" required></DropDown>
</StackLayout>
<Label [text]="validation.valid ? 'Tudo OK!' : 'Campos sem preencher'"> </Label>

For form fields, I saw that it is possible to use id passing as an ngModel, and recovering that component with the parameter ". Valid", as in the example:

<StackLayout class="p-20">
    <Label text="Required Textfield" class="h1 text-center"></Label>
    <TextField required hint="fill this out..." [(ngModel)]="textField" #elementModel="ngModel"></TextField>
    <Label class="validation" [visibility]="elementModel.valid ? 'collapse' : 'visible'" text="Field is required" ></Label>
    <Label [text]="element.className"></Label>
    <Label [text]="elementModel.valid"></Label>
    <Button [visibility]="elementModel.valid ? 'visible' : 'collapse'" text="Save" class="btn btn-primary"></Button>
</StackLayout>

What is the best way to validate all fields, without having to call all the elements in the Label to make a conditional?

1 answer

0


When working with Nativescript/Angular I think the ideal would be to work with Reactiveforms. A login page for example:

export class LoginComponent implements OnInit {
    public loginForm: FormGroup;

 public ngOnInit() {
        this.loginForm = new FormGroup({
            userName: new FormControl(null, [Validators.required]),
            userPassword: new FormControl(null, [
                Validators.required,
                Validators.minLength(6),
            ]),
        });
    }

public onLoggingIn() {
        const email = this.loginForm.get('userName').value;
        const password = this.loginForm.get('userPassword').value;

        if(this.loginForm.valid){
         // Faz alguma coisa com o formuário.
        }

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.