Limiting input to a set of characters while also displaying those characters - javascript

I have seen in a few "username" fields where you type in a username, and below it, in something like a span, it will append it to a url. A lot like what is happening as I type this in StackOverflow at the bottom.
I would like to show only allowed characters from a list, ignore any input of characters not in that list.
I am really new to JS. In this case, I am using Jquery, and have a sort of works with some parts, and other parts I do not, or I have not gotten there yet.
Desire:
Input form field accepts only characters from a list, others are ignored.
Get the new key as entered, and append it to an element.
Here is the mess I have so far:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keyup(function(e) {
var entered = $('#cart-name').val();
entered = entered.toUpperCase();
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
// fromCharCode always returns uppercase?
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
var pos = allowed.indexOf(entered_char);
console.log('position is: ' + pos);
if (pos <= 0) {
console.log('does not contain');
} else {
console.log('contains');
}
$('#live').text(entered);
console.log(entered);
});
});
</script>
In the html I have:
<input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
<br />
http://example.com/
<span id="live"></span>
<br />

Why not use a regular exprsession to replace non alphanumeric characters?
entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');

Looking at your comments, you have some confusion over the different Key events:
keyup (and keydown) tell you which physical key has been pressed, while keypress will tell you which character has been typed - which is why you're always getting uppercase letters from fromCharCode.
I'm using something like this to sort out urls:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keypress(function(e) {
var entered = $('#cart-name').val();
// Regular Express to perform match on all alphanumeric characters,
// and - and _
var matchPattern = /[\w/_/-]/g;
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
if (entered_char.match(matchPattern)) {
$('#live').text(entered + entered_char);
}
else if (enteredKey == " ") {
// Replace spaces with hyphens for SEO
$('#live').text(entered + "-");
}
});
});
</script>
Should see you right.

Related

Remove characters from a string that are not firstname/surname characters

Please see the code below:
#HostListener('paste', ['$event'])
onPaste(event) {
var test = event.clipboardData.getData('text');
var removedNumbers = test.replace(/[0-9]/g, '');
}
Numbers are removed from the pasted text. It is a surname field, so should also exclude characters like {[}] etc.
How can I remove characters that are not valid for a name? I have read lots of simlar questions today like this one: how do i block or restrict special characters from input fields with jquery?. However, I have not found an answer to my specific question.
[^ ] matches anything(including space) that is not enclosed in the brackets, so you could place all characters you don't want to be removed inside the bracket. Note, however, that you have to escape special characters if they are part of the match. Also note that
you can specify a range of characters by using a hyphen, but if the
hyphen appears as the first or last character enclosed in the square
brackets it is taken as a literal hyphen to be included in the
character set as a normal character.
const regex = /[^a-z,' -]/gi;
console.log("Conan O'Brien".replace(regex, ''));
You may also use Unicode character ranges for non-English names, for example
for Chines 4e00 to 9fa5,
for most of Latin 0061 to 007A & 00DF to 00F6 & 00F8 to 01BF & 01C4 to 024F
for Geʽez 1200 to 135A
const regexLatin = /[^\u0061-\u007A\u00DF-\u00F6\u00F8-\u01BF\u01C4-\u024F ]/gui;
const regexChina = /[^\u4e00-\u9fa5 ]/gui;
const regexGeez = /[^\u1200-\u137F ]/gui;
console.log("Björk Guðmundsdóttir".replace(regexLatin, ''));
console.log("陳港生".replace(regexChina, ''));
console.log("ምኒልክ".replace(regexGeez, ''));
However, this is not an exhaustive list, you may refer to the List_of_Unicode_characters to make adjustments for your specific need.
Trying to match all names from 'all' languages could be very hard. The good news, however, is that Unicode_Property_Escapes are part of the ECMAScript 2020 Specification( currently on draft stage ) which will simplify the process a lot.
For example to match for Latin characters, you would use: /\p{Script=Latin}/u,
and to match for letters from 'all' languages, you would use: /\p{Letter}/gu or the short form /\p{L}/gu
Try this.
Vanilla Javascript
document.addEventListener("paste", event => {
event.preventDefault();
let clipboardData = event.clipboardData.getData("Text");
clipboardData = clipboardData.replace(/[0-9_!¡?÷?¿/\\+=##$%\ˆ&*(){}|~<>;:[\]]/g, "");
let allowedPasteTarget = ['textarea', 'text']
if (allowedPasteTarget.includes(document.activeElement.type)) {
let prevText = document.activeElement.value;
document.activeElement.value = prevText + clipboardData;
}
});
//To handle the copy button, [Optional]
document
.getElementById("copy-text")
.addEventListener("click", function(e) {
e.preventDefault();
document.getElementById("text-to-copy").select();
var copied;
try {
copied = document.execCommand("copy");
} catch (ex) {
copied = false;
}
if (copied) {
document.getElementById("copied-text").style.display = "block";
}
});
<div>
<input type="text" id="text-to-copy" placeholder="Enter text" />
<button id="copy-text">Copy</button>
<span id="copied-text" style="display: none;">Copied!</span>
</div>
<div>
<textarea name="paste-area" id="paste-area" cols="30" rows="10" placeholder="Paste it here"></textarea>
</div>
Angular
#HostListener('paste', ['$event'])
onPaste(event) {
var test = event.clipboardData.getData('text');
var removedNumbers = test.replace(/[0-9_!¡?÷?¿/\\+=##$%\ˆ&*(){}|~<>;:[\]]/g, '');
let allowedPasteTarget = ['textarea', 'text']
if (allowedPasteTaeget.includes(document.activeElement.type)) {
let prevText = document.activeElement.value;
document.activeElement.value = prevText + clipboardData;
}
}

Validation for not more than one decimal (i.e 2.2 not 2.2.3)

I want to create a script function which will validate if the user input contains more than one decimal i.e 2.434 should be the correct number but if the user tries to input a NUMBER LIKE 2.4.5.6 it will not take the input in the field. It will take only number after a decimal point but not another single decimal point. no 2.2.2. but 2.2222. Will use it in a .net page.
tried different patterns like ^-{0,1}\d+.{0,1}\d*$ but could not get result. added the function i am already using. need to add the decimal part in the given code.
function isNumberKey(evt) {
var first;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
return true;
}
if (charCode == 46 || charCode > 31 && (charCode < 48 ||
charCode > 57))
return false;
return true;
}
text box will take input when 2.22 or 3.455654 but won't take 2.3.34.4. when the user writes something like this the cursor won't change the position or take the input number.
The code provided does not validate the entire string. It just checks that the key pressed is a digit, which does not help much. There are many ways to do what you want:
1- Browser validation using type="number":
You can use an input with type "number"; then the browser will do a validation on its own before the form submits (this also accepts integers though):
<input type="number" name="decimal" />
2- Browser validation using the patternattribute:
A handy property you can set for inputs is the pattern attribute. You can set it to the desired regex, and the browser will make sure the user's input matches the regex before submitting the form.
<input type="text" name="decimal" pattern="^-?\d+\.?\d*$" />
3- Custom validation with Javascript:
This approach definitely gives you more flexibility, and allows you to validate once the user typed the input, instead of validating on form submit.
Assuming you have a text input, you can listen to the onchange event to validate the entire string, after the user has finished typing their input.
Edit: As for the regular expression, you need to escape the dot, so replace (. by \.). Plus, {0, 1} is equivalent to ?, as pointed out by #CodeManiac in the comments.
var input = document.getElementById("decimal-input");
input.onchange = function() {
var text = this.value;
if(!text.match(/^-?\d+\.?\d*$/)) {
this.value = ""; //clear input
console.log("Please enter a valid decimal.");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="decimal-input" placeholder="Enter a decimal..."/>
</form>
in the event target is the reference to the input element. So you are able to obtain the whole string
function isNumberKey(evt) {
s=evt.target.value;
console.log(s);
if (s.length !==0){
arr=s.split(".");
if (arr.length>0){
return false;
}
///... other checks...
}
there might be also a dirty way to check the whole number
try {
x=eval(s*1) ;
} catch (ex){
return false
}
or just do it on the enter key to implement a tiny calculator in your input ;)
Funtion setupField is called with the id of an input field to be initialized with an onkeyup event that will only allow valid input to be entered into the field. The regular expression it uses allows an optional + or - sign. The number itself can be of the format: 123, 123., 123.45, or .45
To allow an initial entry of the +, -, or . characters, the regular expression must also consider these characters to be legal input. When the form is submitted, there is always the possibility that only one of these 3 characters or no characters at all have been entered. It is easy enough to test for a valid decimal number by testing isNan(parseFloat(input)) against the input.
^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$
<!doctype html>
<html>
<head>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta charset="utf-8">
<script>
function setupField(field)
{
let re = /^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$/;
field.autocomplete = "off";
field.saveValue = field.value;
field.onkeyup = function() {
var v = field.value;
if (v === '' || re.test(v)) {
field.saveValue = v;
}
else {
field.value = field.saveValue;
}
};
field.onchange = function() {
var v = field.value;
if (isNaN(parseFloat(v)))
console.log('You entered invalid input.');
};
}
function init()
{
setupField(document.getElementById('x'));
}
</script>
<body onload="init();">
<input type="input" id="x" size="10">
</body>
</html>

compare Two field if the field is in the content of other field using javascript after submit button clicked

Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online

How to check if a string contain a list if characters which are not in english

I want to valid textbox text. the textbox is for a phone number so, of course, letters and anything other the number I used different kinds of code
ex
$(document).ready(function () {
$("#sub").click(function () {
var regex = /[$%^&*()_+[]{}<>?]אבגדהוזחטיכךלמםנןסעפצקרשת \"/
var bleangth = $('.bphone').val().length;
var eleangth = $('.ephone').val().leangth;
var cbphone = $('.bphone').val();
var cephone = $('.ephone').val();
if (bleangth < 3 || eleangth < 7) {
$('#bad').removeClass("error");
$('#short').addClass("error");
}
else
if (regex.test(cbphone) || regex.test(cephone)) {
$('#short').removeClass("error");
$('#bad').addClass("error");
}
else {
$('#bad').removeClass("error");
$('#short').removeClass("error");
//$('h3').removeClass("snerror")
}
alert( "end " + regex.test(cephone) +" start " + regex.test(cbphone));
});
As you see I entered letters from different language but for some reason the code can't "read" it and return true is there a way maybe to get string split it to array and then use it? or different code or something I need to add/ download
Thank you in advance
You can make regular expression with unicode value
var regex = /^[\u05d0-\u05ea]|[$%^&*()_+{}<>\]\[?]$/
Example
$(document).ready(function(){
var regex = /^[\u05d0-\u05ea]|[$%^&*()_+{}<>\]\[?]$/
$("#buttonCheck").click(function(){
alert(regex.test($("#text").val()));
});
});
Example Link
If requirement is for only numbers to be input you should be able to use NOT operator ! operator with RegExp /\D/ ; e.g.; !/\D/.test(/*input*/) where true would be result if input is a digit, false if input is not a digit.
An approach using HTML5 <input> element with pattern attribute set to \d+, required attribute; <label> element, CSS :focus, :invalid , adjacent siblings selector +
input + label {
display:none;
}
input:focus:invalid + label {
display:block;
color:red;
}
<input type="text"
pattern="\d+"
placeholder="Please input digits 0-9"
required /><label>Invalid input. Please input digits 0-9</label>

How do I change a string into a password?

I have:
$('#pass').on('keyup keydown', function() { //the password input
$('#pass-result').text( $(this).val() ); //the input's bullet's, not string value
});
The text value of the password is printed as the input's string. How do I convert it to the password's masqueraded bullet form (•)?
If you're looking for dots to appear in the field when text is typed in it, you should use <input type="password"> instead of <input type="text">:
<input type="password" id="pass" />
which you would get the text from with $("pass").val().
It looks like you want a string of dots instead. To accomplish this, use:
var dots = Array($("pass").val().length + 1).join("•");
To explain:
$("pass").val() gets the text
$("pass").val().length gets the length of that
Array($("pass").val().length + 1) gets a new Array whose length is 1 more than the length of the password text
Array($("pass").val().length + 1).join("•") returns each element of the Array with a dot inserted between each - which is why we needed 1 extra, otherwise we would get a fencepost error.
According to the fact that you only want to parse a string of dots . what you gonna do is (IF YOU USE 2 INPUTS!)
function getKeyCode(event) {
event = event || window.event;
return event.keyCode;
}
$('#pass').on('keyup', function(e) { //the password input
if (getKeyCode(e) == 8) {
$('#pass-result').val($('#pass-result').val().slice(0,-1) );
}
else {
$('#pass-result').val($('#pass-result').val() + '•');
}
});
didnt test the code though. but it should add a • to the #pass-result on ever key-down in the #pass field. it doesnt remove any on backspace though..
http://jsfiddle.net/7810squo/
if you wanna do it with a <span> you need to use .html()
function getKeyCode(event) {
event = event || window.event;
return event.keyCode;
}
$('#pass').on('keyup', function(e) { //the password input
if (getKeyCode(e) == 8) {
$('#pass-result').html($('#pass-result').html().slice(0,-1) );
}
else {
$('#pass-result').html($('#pass-result').html() + '•');
}
});
http://jsfiddle.net/u9kdeewd/
EDIT: updated code and provided jsFiddle link

Categories

Resources