Required field with prompt alert


#1

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


#2

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


#3

didnt find anything yet , keep looking


#4

import { Alert} from ‘ionic-angular’;

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

try it !


#5

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


#6

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:.


#7

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


#8

stuck with the same found anything?


#9

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();
}

}


#10

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();
    }

}