Required field with prompt alert

hi guys!
there is a way to set that a field is required with prompt alert?

1 Like

I’m having the same problem… Did you solve it?

didnt find anything yet , keep looking

import { Alert} from ‘ionic-angular’;

let alert = Alert.create({
title: ‘Error’,
subTitle: ‘Error’,
buttons: [‘OK’]
});
this.nav.present(alert);

try it !

Has anyone found a solution to get a required field inside an alert?
It’s a quite common feature, that might deserve an issue on github, I didn’t find anything about that

I’m also searching for this, I might have to switch to ModalController because I have no control over the input of the alert :frowning:.

What I did is to be recursive (call the same function again) in case the data.name it’s empty.

1 Like

stuck with the same found anything?

try this :

import { AlertController } from ‘ionic-angular’;
export class DatamemberPage {

constructor(public alertCtrl: AlertController) {
}

failedAlert(text) {
  let alert = this.alertCtrl.create({
	title: 'Failed',
	subTitle: text,
	buttons: [{
	text: 'OK',
		handler: () => {
			this.AddData();
		}
	}]
	
  });
  alert.present();
}

AddData() {
	let alert = this.alertCtrl.create({
	title: 'Add Data User',
	inputs: [
	  {
		name: 'username',
		placeholder: 'username'
	  }
	],
	buttons: [
	  {
		text: 'Cancel',
		role: 'cancel',
		handler: data => {
		  console.log('Cancel clicked');
		}
	  },
	  {
		text: 'Save',
		handler: data => {
		  if(data.username == "") {
			this.failedAlert("username is required");
		  } else {
			  console.log(data.username)
		  }
		}
	  }
	]
	});
	alert.present();
}

}

1 Like

Hi all, I want to share a solution I improved yesterday after reading this thread. I created an injectable PromptService that allows me to inject it in any module to present a prompt just calling promptService.showPrompt(‘title’, ‘text’, inputs, callback, cancel_callback, present).
The optional ‘inputs’ arrays parameter support an optional ‘required’ boolean in the items that add validation.
The optional ‘present’ last parameter allows you to just get the alert object in order to manipulate it before calling present() manually.
Let me know if you find it useful or if you have any question.

import { Injectable } from '@angular/core';
import { AlertController } from 'ionic-angular';


@Injectable()
export class PromptService {

    constructor(
        private alertController: AlertController,
    ) {
    }

    public showPrompt(title: string, message: string, inputs: any[], cb: Function, ecb: Function = ()=>{}, present: boolean = true) {
        inputs = inputs || [];
        const cleanedInputs: any[] = this.cleanInputs(inputs);
        let prompt = this.alertController.create({
            title: title,
            message: message,
            inputs: cleanedInputs,
            buttons: [
                { text: 'Cancel', handler: ecb },
                { text: 'OK', handler: data => {
                        this.validate(data, title, message, inputs, cb, ecb, present);
                    }
                }
            ]
        });
        present && prompt.present();
        return prompt;
    }

    protected cleanInputs(inputs: any[]): any[] {
        return inputs.map(item => {
            let cleanedItem: any = Object.assign({}, item);
            delete cleanedItem['required']
            return cleanedItem;
        });
    }

    protected validate(data: any, title: string, message: string, inputs: any[], cb: Function, ecb: Function = ()=>{}, present: boolean = true) {
        let errors: any[] = [];
        let requiredInputs: any[] = inputs.filter(item => item['required']);
        for (let requiredInputFor of requiredInputs) {
            if (data[requiredInputFor.name] === '') {
                let fieldName: string = requiredInputFor['placeholder'] || requiredInputFor['name'];
                errors.push(`Field ${fieldName} is required.`);
            }
        }
        if (errors.length) {
            this.invalidAlert(errors, title, message, inputs, cb, ecb, present);
        }else{
            cb(data);
        }
    }

    protected invalidAlert(errors: string[], title: string, message: string, inputs: any[], cb: Function, ecb: Function = ()=>{}, present: boolean = true) {
        let alert = this.alertController.create({
            title: 'Error',
            subTitle: errors.join('\n'),
            buttons: [{
            text: 'OK',
                handler: () => {
                    this.showPrompt(title, message, inputs, cb, ecb, present);
                }
            }]
        });
        alert.present();
    }

}

I am using this;

addItem(id, description, quantity, price) {
    let alert = this.alertCtrl.create({
        .....
        ........
        buttons: [
            {
              text: "Save",
              role: "save",
              cssClass: "btnSave",
              handler: data => {
               //here is what ensures that the inputs have some data
                if (
                  data.description == "" ||
                  data.quantity == "" ||
                  data.price == ""
                ) {
                  this.presentToast();
                  alert.dismiss();
                  return false;
                } else if (
                  ((data.id = this.id),
                  data.description,
                  data.quantity,
                  data.price)
                  .....
                   ......

    })
}

presentToast() {
    let toast = this.toastCtrl.create({
      message: "field(s) cannot be empty",
      duration: 1000,
      position: "top"
    });

    toast.onDidDismiss(() => {
      this.addItem(this.id, "", "", "");
    });
    toast.present();
  }
1 Like

Another solution is to use manipulate the DOM by querying the HTML elements.

Here is the full example https://stackoverflow.com/a/56352849/3950497