How to validate window.prompt in javascript? - 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.

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.

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.

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.

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

Related

question about input validation after element loses focus

I started learning javascript, and I am trying to make a little project to play around.
I want to validate that the input field for username contains only letters (uppercase or lowercase) and when the value is correct, to outline the field with a color. (I don't care about the design, i care about functionality since it's purpose is for learning).
I have this code: https://jsfiddle.net/7zcv4g1m/1/
const userField = document.querySelector('#user .user');
const passwordField = document.querySelector('#password .password');
const regEx = /^[a-zA-Z]+$/g;
function checkUser() {
// userField.setAttribute('class', 'user');
let userText = userField.value.substring(0, userField.value.length);
let expr = regEx.test(userText);
if (expr == true && userText.length > 0) {
userField.setAttribute('class', 'user test');
} else {
userField.setAttribute('class', 'user');
}
}
userField.addEventListener("focusout", checkUser, false);
My problem is this: at first run, if I click on the element and type a correct text, it outlines the input as expected when I focusOut of the element. The issue is when I click back in the element and just click somewhere outsite of the element to trigger focusout event, without modifying anything in the text. Somehow, my regex condition (the expr variable in the code) is considered to be false, instead of being true, and it turn the element's output back to grey instead of green. If I click back in and after out, it turns back the input border to green.
I don't understand why is this happening and where I made a mistake. Or maybe I wrote the code wrong. If anyone can please give me a hint, will be much appreciated.
It's caused by regEx.test(userText). This should work:
function checkUser() {
// userField.setAttribute('class', 'user');
let userText = userField.value.substring(0, userField.value.length);
let expr = userText.match(regEx);
if (expr && userText.length > 0) {
userField.setAttribute('class', 'user test');
} else {
userField.setAttribute('class', 'user');
}
}
delete modificier g in RegEx, like as
const regEx = /^[a-zA-Z]+$/

How to allow non alphanumeric characters in a html5 / jquery mobile form input

I have a form input field for a to-do list style app for iOS using cordova. I'd like the user to be able to enter characters such as: ! % & +
However these caused the app to crash. My temporary fix was to restrict the key input on the form field using the .keypress function. However I'd like to find a way for users to be able to include these characters in their list items. (I also realized that adding a blank space as the only input causes the app to crash.)
I've see a lot of Q+As for validation that restricts the use of these characters but is it possible to be able to use them in a form input?
Thank you!
/* Form to make a new list item */
$('.formMain').submit(function () {
var key = Date.now();
var text = $('#todo').val();
var textTrim = text.replace(/ /g, '').toLowerCase();
var checked = false;
var quantity = $('#quantity').val();
// if the inputs are blank
if (text.length == 0) {
return false;
}
// if item already on list
else if ($('.list #' + textTrim).length) {
alert(text + " already on list!");
}
// if the input box is not empty run the template function
else if ((text.length > 0) === true) {
var html = template(text, textTrim, key, checked, quantity);
$('.list').append(html);
itemListArray.push({ key: key, text: text, textTrim:textTrim, checked: checked, quantity: quantity});
// Save the item list array
if (window.localStorage) {
window.localStorage.setItem('itemListArray', JSON.stringify(itemListArray));
}
$('#todo').val("");
$('#quantity').val("");
}
return false;
Thank you for the push in the right direction noahnu.
The crashes were occurring when meta-characters were being assigned to my "textTrim" variable. I believe the issue is when that variable contains meta-characters and is assigned to the ID of a html tag. (I'm using textTrim as a way to uniquely identify items for validation purposes).
var textTrim = escapeHtml(text).toLowerCase();
The problem was solved by creating a escapeHtml function that replaces each character with its decimal value. e.g.
function escapeHtml(text) {
return text
.replace(/&/g, "38") // etc

Conditional statements with user input

I'm working on a textbot project, where if I input some text in a textbox, the bot spits out something in the console, fairly simple. However, I've run into a problem that I am very frustrated over, and haven't managed to solve. There's probably a simple solution to this, but I can't find it.
What I want to do, is having the textbox accept a command that consists of the user input + a variable that the user inputs. Something like this:
case "input " + condition {
//do something with condition
}
My question is how do I make the textbox differ between the input and the condition? I hope this question isn't way too hard to understand, but I don't know how else to explain it :P
Edit:
Example:
Textbox input:
"!locate p.actionValue"
Then depending on what actionvalue the person inputs, this should return something like:
if (actionvalue = 32) {
//do something if actionvalue is 32
}
But how do i differ between the command and condition?
You can use a regular expression to match the input and get the condition:
var match;
if (match = input.match(/^!locate (.*)/)) {
var condition = match[1];
// do something with condition
}
You can get more general:
var match = input.match(/^!(\S+)\s+(.*)/);
if (match) {
var command = match[1];
var arg = match[2];
switch (command) {
case 'locate':
...
break;
}
}
You can split your text by "input " and then you will get the command
// array separated by 'input '
var command = textbox.split('input ');
// here you got your command: command[0]
of course you'll need to validate that it actually has 'input ', and what happens in cases like 'input input '

JavaScript First Letter Capitalisation Not Working

Firstly, this is my first time working with JavaScript so it is probably just me missing something very simple.
All I want to do is get the value of a text box and make an alert with the first letter capitalised. I have everything working, the first letter isn't actually being capitalised.
This is how I am calling the function:
else
{
input = document.getElementById("search").value;
'input'.search();
alert(input);
}
This is the function it self:
function search(string)
{
return string.charAt(0).toUpperCase();
}
this is the correct code
else
{
input = document.getElementById("search").value;
input =search(input);
alert(input);
}
Try this:
input = search(input);
Instead of:
'input'.search();
You aren't changing input at all. Try:
else
{
input = document.getElementById("search").value;
alert(search(input));
}
If you want to permanently change input Try:
else
{
input = document.getElementById("search").value;
input = search(input);
alert(input);
}
A couple of things wrong here,
firstly,
search(input)
instead of
'input'.search()
secondly,
string is immutable so you'll have to do,
input = search(input);
alert(input);
.
.
.
function search(str) {
return (str.replace(str.charAt(0), str.charAt(0).toUpperCase()));
}
Your question is not pretty clear to me, but I assume that you want, if your input string is "hello" , you want the output as "Hello".
Try this
call the method and alert the message:-
alert(search(input));
in the method:-
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase()+this.slice(1);
}
var searchField = document.getElementById("search");
var query = searchField.value;
searchField.value = query.capitalize();
function search(query) {
// query api or something...
}
The answers are correct, but you will have only the first letter in the alert box.
If you don't want only the first letter, here is the solution:
function search(string)
{
return string.substring(0,1).toLocaleUpperCase() + string.substring(1);
}
From https://stackoverflow.com/a/30123193/2379208

Javascript replace function won't remove the string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 8 years ago.
I have no idea why this doesn't work, but doing some validation functions and trying to output a dynamic message to an alert when they hit submit and forgot to fill out a field. It works only on the second click of the submit button, as far as removing the string, everything else works when it should.
Here's the code:
var fname = $('#fname');
var lname = $('#lname');
function validatefname(){
var a = fname.val().length;
if(a < 2) {
fname.prev().addClass("error");
if(msg.search("First Name") == -1) {
msg+= "-Please enter your First Name\n";
}
return false;
} else {
fname.prev().removeClass("error");
msg.replace(/Please enter your First Name\n/g, "");
return true;
}
}
fname.blur(validatefname);
fname.keyup(validatefname);
step4submit.click(function(){
if(validatefname()) {
step4form.submit();
return true
} else {
msg+= "\nPlease fill out the fields marked in red";
alert(msg);
msg = "";
return false;
}
});
String.replace returns a new string, rather than editing the string that makes the replace call.
You need
msg = msg.replace( blah )
In JavaScript, Strings are immutable, they can never change. So if you are calling a function to modify a string in some way, that function will return a new string with your changes, rather than modify the original string.
Change the line that is performing the replacement to save the result of the replacement back into the original variable, like so:
msg = msg.replace(/Please enter your First Name\n/g, "");
(there are various performance and safety reasons for this, but that is for another day/another question).
Try changing
msg.replace(/Please enter your First Name\n/g, "");
to
msg = msg.replace(/Please enter your First Name\n/g, "");

Categories

Resources