Szabolcs Antal
Szabolcs Antal

Reputation: 957

How to validate window.prompt in javascript?

Is there a way to validate the text of the input textBox of the prompt box displayed by calling window.prompt() in javascript?

I mean something like to not to close the prompt box when clicking its OK button if the string written in its input textBox contains numbers or other illegal chars defined by me, etc.

Upvotes: 1

Views: 2833

Answers (4)

Rounin
Rounin

Reputation: 29493

I came across this exact problem today while writing a bookmarklet which requests user input.

It struck me that it's possible to validate window.prompt simply by using a while loop:

let promptedAnswer = null;

while (promptedAnswer !== 'spoon') {

  promptedAnswer = prompt('Complete this phrase: "There is no [ ]."');
}

Working Example:

let chosenNumber = 0;

while ((chosenNumber < 1) || (chosenNumber > 10)) {

  chosenNumber = prompt('Choose a number between 1 and 10:');
}

console.log('Your chosen number is ' + chosenNumber);

Upvotes: 0

Mudassir Ali
Mudassir Ali

Reputation: 8041

var obj = {};

function validate( str ){
    return !! str; //or your own validation
}

function setName ( error_message ) {
    var name = prompt( (error_message || '') + "Enter a name: ");

    if ( ! validate( name ) ) {
        setName( 'Invalid name entered\n' );
    } else {
      obj.name = name;
    }
}

If you really want to use only prompt then this is the solution. But, I'd suggest you to use a modal dialog or create your own component.

Upvotes: 1

RemyG
RemyG

Reputation: 496

You can't validate the input of a prompt before closing it. You could simulate this by creating your own type of prompt, or using jQueryUI.

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72927

No, there is not.

.prompt is native functionality that can't be modified.

If you want input validation, you're going to need to use a custom prompt. It might be worth looking into UI libraries like jQueryUI, for example.

Upvotes: 2

Related Questions