Disallow input if it matches predefined values - javascript

I would like to disallow certain input into an html input field.
Manually type in a value in a "Select" / Drop-down HTML list? this question covers how to recommend values while letting the user type.
I would like to let the user type and 'blacklist' certain values if they matches one of my predefined values and show a warning.
What is the easiest way to achieve this?

function myFunction(e) {
const val = e.value;
const blacklist = ["12345678", "qwerty"];
if (blacklist.indexOf(val) >= 0) alert("Blacklist");
}
<p>A function is triggered when the user releases a key in the input field.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction(this)">
You need to play with keyup event and provide a blacklist. You can do whatever you want with val, you could check if it's one of blacklist values(example above) or if it matches a RegExp pattern.

You can also use a regular expression. It's only possible to submit the form if the text does not contain foo.
<form action="#">
<input type="text" name="xx" pattern="^((?!foo).)*$"><br />
<input type="submit">
</form>

Related

How to limit a dot string to only one character even when holding down a non-number key

I'm creating a input validation to allow only a numeric and dot input.
It does limit the dot character to one onkeypress but when holding down a non-number key it's not.
<input class="form-control" type="text" onkeyup="this.value=this.value.replace(/[^0-9.{1}$]/g, '').replace(/(\..*)\./g, '$1');" />
How can i limit the dot string to one even when holding down a non-number key?
You shouldn't need javascript here: use input with type number (see MDN). If the typed user input is invalid (it may contain more dots), the input has no value (check it with the button of the snippet). For example:
document.querySelector("button").addEventListener(
"click",
() => {
const val = document.querySelector("input").value;
console.log( val || "Invalid");
}
);
<input type="number" step="0.1" min="1" max="20" value="1.0">
<button>show value</button>
You can use
^(?=^[^.]*\.?[^.]*$).+$
<form>
<input type='text' pattern='^(?=^[^.]*\.?[^.]*$).+$'/>
<button typ='submit'>submit</button>
</form>
Note:- If you need one . to be must you can change above regex to
^(?=^[^.]*\.[^.]*$).+$
You could use <input type="number" /> or <input pattern="[0-9]*\.?[0-9] /> as the others have suggested.
However,
If you want to do it "manually"
You could use the onkeypress attribute. This is the event which fires for every repetition of a character. After firing this event, the browser updates the input value.
Canceling the event
If we return a false like such: onkeypress="return false", you will notice that the input value won't update anymore, no matter what key you press. We can even add a condition: onkeypress="if(event.key != '0') return false;". In this case, you will only be able to write 0s in the input.
So, this is the event during which we will have to check, and make up our mind if we are going to allow the newly pressed key to have an effect. We will return true or false accordingly. However, there is only one little problem.
Composing the new value
Before we are going to decide if we allow the newly pressed key to have an effect, we need to see what effect it would have. We need to see how the input value will look like after this event. So we are going to compute it. Right now, the input still contains the current (without the new character) value.
Implementation
The JavaScript function:
function checkNumber(input, event){
//- We have the old value in input, and the currently pressed key in event.key
//- So we have the compute the new to be value of the input, to check if it's correct
//- To do this, we break the text into an array of characters, and insert the key
//- at the cursor's position - Check on MDN what Array.prototype.splice() does
var newValue = input.value.split('');
newValue.splice(this.selectionStart, this.selectionEnd-this.selectionStart, event.key);
newValue = newValue.join(''); //- Put it back into string form
return /^[0-9]*\.?[0-9]*$/.test(newValue);
}
And to use it:
<input class="form-control" type="text" onkeypress="return checkNumber(this, event);" />

Javascript to replace all the input.value by '*' like a password typing

I have a
<input id="TxtBox" runat="server" autocomplete="off" onkeypress="">
And while doing the keypress, directly with js code, it replaces all the characters for '*'. Like a password typing.
Edit: 2022
As i read this old question i found imprecision why i wanted to avoid type="password" at that time. It was because if that attribute were in the tag the browser would remind a old password and it was annoying.
Edit:
I passed all day trying do put the autocomplete=off on all of my inputs to the browser stop asking password while someone is filling a form on my site, ddnt worked(a tried a few more things). And i thought in this type of solution i tried the javascript replace function but it only returned one char and decided to ask about a complete sequence of '*' while writing in a input. Tks for all the help.
sorry if i wasnt clear in the context i was just thinking in the code. i thought in some old i did before in C language but anyway i asked.
Edit:
I asked help how to do this in JS i did some stuff on keypress with JS functions like replace i did some code but i simply erased it and asked for some help. Next time i will post code to have some kick start code. I was doing something like
onkeypress="this.value=this.replace(this.value,'*')"
Tks in advance.
This is for in a visible input see a password typing and in a hidden i have it.
note: i want to avoid type="password"
Why do you need JavaScript to accomplish what HTML gives your for free? The element exposes all the same attributes/properties so you can still use it like a text box.
<input type="password">
If you feel you must reinvent the wheel, this can be done by using two fields. The user will type in the first and it will display the mask character and the actual key will be stored in a hidden input field for processing:
// Get references to DOM elements:
var txt = document.getElementById("txtMask");
var hdn = document.getElementById("pass");
// This keeps track of how many characters should be displayed
var maskLen = 1;
// Set up input event on first box
txt.addEventListener("keydown", function(evt){
// Manually put the right amount of mask characters into the box
// and update the maskLen value
var str = '#'.repeat(maskLen++)
this.value = str;
// Cancel the event and stop bubbling
evt.preventDefault();
evt.stopPropagation();
// Set the actual typed data into the hidden field
hdn.value += evt.key;
// Just for testing:
console.clear();
console.log("Actual data is: " + hdn.value);
});
<input type="text" id="txtMask" autocomplete="false">
<input type="hidden" id="pass">
Use type="password"
Like this:
<input type="password" id="TxtBox" runat="server" autocomplete="off" onkeypress="">
You can also do one of these:
input { -webkit-text-security: none; }
input { -webkit-text-security: circle; }
input { -webkit-text-security: square; }
input { -webkit-text-security: disc; /* Default */ }
You can use those without having a type="password"

How to edit dynamic form fields to create a single hidden field comprised of the value of two fields

I need to send a form off to where a single hidden field is comprised of two of the other fields that will be dynamically populated by a user (post/zip code and first line of address) where after regular expression only the numbers remain "123|456".
I have attempted to start, using the code below, where I monitor the output in the console. I have managed to dynamically edit a textfield so that all that is shown are the numbers but this is not suitable for a user. So I was trying to store the edited textfield data into the hidden field whilst leaving the complete line of address but I could not see how this can be done.
Also, can someone explain why if I remove the commented line the variable is not stripped of any letters albeit just 1?
$(document).ready(function() {
$("#testMe").on('propertychange change click keyup input paste', function() //attaching multiple handlers
{
var removedText = $("#testMe").val().replace(/\D/, '');
$("#testMe").val(removedText); //only removes once if removed
console.log(removedText);
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="hidden" id="hide" value="">
<input type="text" id="testMe" value="">
<span id="test2"></span>
The question was kind of unclear to me, but I did my best to answer.
https://jsfiddle.net/ccu6j6xu/
<input type="hidden" id="hide" value="">
<input type="text" id="zip" value="">
<input type="text" id="address" value="">
<span id="test2"></span>
In the HTML, all I did was add another input, because I think that's what you wanted to do?
$(document).ready(function() {
$("#zip, #address").on('propertychange change click keyup input paste', function() {
var concatText = $("#zip").val().replace(/\D/g, '') + "|" + $("#address").val().replace(/\D/g, '');
$("#test2").text(concatText);
$("#hide").val(concatText);
});
});
Then in the JavaScript, I changed the selector to match the new inputs, and then I changed the function.
The first line of this function defines a variable concatText to hold the values of each input concatenated with a | character between. Each one has regex applied to remove the letters for the final value. Then the next line changes the value of the span to display, and the final line applies this value to the hidden input.
Again, the question was kind of confusing to me, but feel free to comment and I can help some more :)
EDIT: reread the question, I think this better answers

JavaScript: How to detect a non empty input text box

I am learning JavaScript and and am working on a To Do list type of application.
Idea: "Add" button is set to disabled in the HTML and only to be enabled when there is at least one character.
My code only works when there is at least 2 characters and can't workout why it doesn't detect the first character.
The other realted question is how do I set the "add" button back to disable if the input box content has been deleted.
HTML
<input id="addToListInput" onkeydown="buttonStatus()" value="" type="text"><input id="addToListButton" disabled type="submit" Value="Add to list" onClick="addToList(this)">
JS
function buttonStatus() {
var input = document.getElementById('addToListInput');
var submit= document.getElementById('addToListButton');
if (input.value.trim() ==""){
submit.disabled=true;
}else{
submit.disabled=false;
}
}
Use keyup instead. By using keydown you are detecting when the key is down, but the textbox value has not changed at that point...
<input id="addToListInput" onkeyup="buttonStatus()" value="" type="text">
onkeydown is fired before the input control is actually fired, if you use onkeyup it should work as you expect.

Javascript to prevent invalid user input

I have written a set of javascript functions that allow me to validate user input on a form. I only want to accept valid input, and impose the following behaviour:
When a user enters an invalid form, I display an alert and inform them that the value entered is incorrect. Crucially, the original (valid) value in the form is not changed.
The value is only changed when the value has been validated.
For example, suppose I want to accept only positive integers in a field.
This is the sequence of events that describes the desired behaviour.
Scenario 1 (valid input)
Form loads with valid default in the input field
User types in valid number
Input field value is updated (as per normal form behaviour)
Scenario 2 (INvalid input)
Form loads with valid default in the input field
User types in INvalid number
Alert box is shown alert('Invalid value')
Input field value is NOT CHANGED (i.e. the value is the same as BEFORE the user typed in the invalid number)
[Edit]
The only problem I am facing at the moment (i.e. what this question is seeking an answer for), is Scenario 2, action point 4. More specifically put, the question degenerates to the following question:
How do I stop the value of a field from changing, if I (somehow) determine that the value being entered by the user is invalid. This is really, all I'm trying to answer.
I am also doing server side checks, this question is just about the front end - i.e. refusing to change a field (form text input) value if I determine that the value is incorrect.
BTW, I am using jQuery, and would like to implement this in a manner that separates behaviour from display (I think this is what is meant by the term 'unobtrusive' ?)
Any suggestions on how to implement this behaviour as described above, would be very much appreciated.
PS: I dont want to use yet another jQuery plugin for this. I should be able to use jQuery + the simple javascript validation functions I have already written.
When loading the page, couldn't you create a hidden form value or js variable in which you store the initial/default value for the field? When they change the form field, validate it, and if it passes, update the hidden field or js variable to match that in the field they updated.
When the input given by the user fails validation, show the invalid entry along with the error message and then update the form field back to the value you have saved which would be either the
default value or the last valid value that they entered.
EDIT:
Note that this is only a quick and (very) dirty example of doing what I explained in my answer above. If you have a lot of inputs, you will probably want to store the values in an associative array instead of in hidden form values, but this should give you a good handle on what I am suggesting. I would also strongly encourage you to NOT use alert boxes for notification of invalid answers.
<html>
<head>
<script type="text/javascript">
function validate()
{
var field1 = document.getElementById("field1");
var saved = document.getElementById("field1_save");
if (field1.value < 0 || field1.value > 10)
{
alert("Field1 value of " + field1.value + " is invalid");
// Change the value back to the previous valid answer
field1.value = saved.value;
return false;
}
// Save the valid input
saved.value = field1.value;
return true;
}
</script>
</head>
<body>
Test User Input
<form name="form1" id="form1" method="post">
<input name="field1" id="field1" type="text" value="2" onblur="validate();"/>
<input name="field1_save" id="field1_save" type="hidden" value="2" />
<input name="btnSubmit" type="submit" value="Submit" />
</form>
</body>
</html>

Categories