Prevent special chars in text area - javascript

I need to prevent special characters to being inserted in the text area. It should work across all browsers.
I've tried to do it but it won't check "~" and "ã" and "á". In this case "ã" get same code as "a".
$('#sms_text').keydown(function(e) {if((e.keyCode>64 && e.keyCode<91) || (e.keyCode>96 && e.keyCode<123) || e.keyCode==8)
{}
else{e.preventDefault();}});
$('#sms_text').keyup(function(e){if((e.keyCode>64 && e.keyCode<91) || (e.keyCode>96 && e.keyCode<123) || e.keyCode==8)
{}
else{e.preventDefault();}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class="form-group" style="width:40%">
<label for="exampleInputEmail1">Email address</label>
<textarea class="form-control" id="sms_text"></textarea>
<div class="text-right">
<h6 class="badge badge-dark"><span id="count_message">0</span>/50</h6>
</div>
</div>
I should expect prevent in that special cases.

Take a look to the jQuery alphanumeric plugin! enter link description here
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});

let textAreaContainer = $('#sms_text');
textAreaContainer.keyup(function(e){
if (e != "") {
if ( /[^\w\d]/.test(e)) {
alert("Please enter only letter and numeric characters");
return (false);
} else { e.preventDefault()}
}
})
this expression match
Match a single character not present in the list below [^\w\d]
\w matches any word character (equal to [a-zA-Z0-9_])
\d matches a digit (equal to [0-9])
or may be a solution with ur approach with this condition on the if
((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57) || k == 190 || k == 188)

Related

Allow all numbers and letters but only this special caracters (# ‘ () + - ? ! / & * »)

I want allow only numbers and letters and this special caracters (# ‘ () + - ? ! / & * ») in JavaScript.
For this moment i have only numbers and letters allow but i want a special caracters. ( # ‘ () + - ? ! / & * » )
$("#test").keypress(function(e) {
$("#error").remove();
var k = e.keyCode,
$return = ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 49 && k <= 57));
if(!$return) {
$("<span/>",{
"id" : "error",
"html" : "No special caracters allow !"
}).insertAfter($j(this));
return false;
}
});
Thank you in advance for your fast reply.
It would probably be easier to use e.key instead, which will give you the actual character, and not the character code, and then you can check the character against a regular expression that contains the permitted characters:
const isOk = /[a-z0-9#‘)(+-?!\/&*»]/i.test(e.key);
if (!isOk) {
// handle error
}
You can use a regex:
[a-zA-Z0-9\[#()+-?!&*‘»]*
you can test it on https://regex101.com/r/sxrFqq/2
Simple regex:
/[a-z0-9\#\'\(\)\+\-\/\&\*\»]/gi

How to add user input at caret position?

I am facing a weird issue regarding a textbox after using validation for preventing special characters.Lets say I enter some text in it.Now if I change the caret position in between the already entered text and try to add text there, the caret automatically jumps to the end of the text.
Any workaround for this?
Note:- I am using IE 11.
Textbox :-
<div class="form-group">
<label data-i18n="rpt_name"></label>
<span class="required">*</span>
<input type="text" class="form-control" id="subNameID">
</div>
The source of error is validation for avoiding special characters.
$('#subNameID').bind('keypress', function (e) {
if ($('#subNameID').val().length == 0) {
var k = e.which;
var ok = k >= 65 && k <= 90 || // A-Z
k >= 97 && k <= 122 || // a-z
k >= 48 && k <= 57; // 0-9
if (!ok) {
e.preventDefault();
}
}
})
Also tried using below solution but gives the same issue.
$("#subNameID").on("keypress keyup paste", function (e) {
if (e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 8)
return true;
this.value = this.value.replace(/[^a-zA-Z0-9\-\._\s]/g, '');
});

javascript to allow only negative and positive numbers and decimal upto 6 digits on keypress

I need to validate a textbox in my cshtml page to accept only negative or positive numbers and upto 6 decimal places. This is what I have tried so far.
function AcceptUptoSixDecimalPlacesWithNegative(event, elem) {
if ((event.which != 46 || $(elem).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9 && event.keyCode !== 0 && event.keyCode !== 45) { //exception
event.preventDefault();
}
}
var text = $(elem).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 6)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9) { //exception
event.preventDefault();
}
}
This is helping me achieve six digits after decimal point but then it allows all special characters and alphabets too.
Any help with this problem would be appreciated.
Thanks.
You could check the value with Regex:
var re = /^-?\d*\.?\d{0,6}$/;
var text = $(elem).val();
var isValid = (text.match(re) !== null);
The Regex means:
^ : beginning of string
-? : one or zero "-"
\d* : 0 to infinite numbers
\.? : 0 or 1 "."
\d{0,6} : from 0 to 6 numbers
$ : End of string
You could use the isNaN() function of JavaScript.
var inputPrevValue = "";
$(document).ready(function () {
$("#numbersOnly").change(function () {
if (isNaN($(this).val()) || $(this).val().length > 6) {
$(this).val(inputPrevValue);
} else {
inputPrevValue = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="numbersOnly">
This is a (very simplistic) example that tests if the input is a number less than 6 characters in length. If not, it'll revert it to the last acceptable value.
***Adding Comment as no access yet!!!
Try Regex "^[0-9]+(.[0-9]{1,2})?$" to verify the text and then proceed with logic.
js code:
var patt = new RegExp("^[0-9]+(.[0-9]{1,6})?$");
var res = patt.test(str);
if res is true then proceed else return false;
Here are a list of functions to help in your question:
Math.sign() checks if its a positive/0, negative/0 and NaN
Number MDN contains a list of number functions
parseFloat()
count digits after decimal post or regex ie. \d+([.\d{1,6}]*)\
In your context, a combination of validations in the following example:
let x = elem;
if(Math.sign(x) === 1 || Math.sign(x) === -1) && ...
// decimal validations
Hope this helps.
Don't validate the keys pressed. There are many ways to change input
value. Handle the oninput event.
You may treat the value as a string and validate using a
regular expression, but I think it's better to combine string and number-related
functions
For example:
<input type="number" step="any" oninput="validate(this)" />
function validate(input){
var number = parseFloat(input.value);
if( number == input.value && input.value.length <= number.toFixed(6).length ){ /* valid! */ }
}
http://jsfiddle.net/tto2yvwj/

Javascript validation - Min/Max number of characters AND must contain number

I have the following problem:
I need to validate an input (password field) with Javascript / jQuery
The rules are:
it must be 8 to 32 characters
it must contain letters AND at least one number
So my logic is the following but I can't seem to be able to implement it
be 8 to 32
if it's NOT 8 to 32 characters and doesn't have numbers
{
jQuery('#passwordfield').addClass('error');
}
I tried the following (just with 0 as number, for test purposes)
if(((jQuery('#passwordfield').val().length <= 7) || (jQuery('#passwordfield').val().length >= 33)) && ((jQuery('#passwordfield').val().indexOf("0") == -1)))
{
jQuery('#passwordfield').addClass('error');
}
The problem with the above code is that it returns true if you type enough characters (8 to 32) and NOT contain a number since the first part of the && is true
Try this :
var p = jQuery('#passwordfield').val();
if(p.length <=7 || p.length >= 33 || !p.match(/\d/) || !p.match(/[a-z]/i))
$('.whatever').addClass('error');
You can use regular expression:-
var val = jQuery('#passwordfield').val();
if(val.length <=7 || val.length >= 33 || !/[0-9]/.test(val) || !/[a-zA-Z]/.test(val))
{
// show error
}
String must contain 0..* letters and 1..* numbers (with a total length of 8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/\d/) == -1) {
jQuery('#passwordfield').addClass('error');
}
String must contain 1..* letters and 1..* numbers (with a total length of 8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/[a-zA-Z]\d|\d[a-zA-Z]/) == -1) {
jQuery('#passwordfield').addClass('error');
}

Text Input: Limit input to numbers (0-9) and the minus sign (-). Not working as expected

I am trying to limit keyboard input in my text field to numbers [0-9] and the minus sign - only (no copy/paste, etc.) and the delete key obviously.
The code works for limiting to numbers and the delete key but it doesn't work for the minus sign - part.
The user should only be able to enter a minus sign - in front of their number, if they try to enter 1 then - it should not input the - but right now the - part doesn't work at all.
Fiddle: http://jsfiddle.net/7XLqQ/1/
I think this piece of code is the issue but it looks fine. It checks that the text input is blank and if so it input the minus sign -.
// Only enter the minus sign (-) if the user enters it first
if (unicode == 45 && input.value == "") {
return true;
}
My full code:
<input type="text" maxlength="10" id="myInput">
<script>
var input = document.getElementById("myInput");
input.onkeypress = function(e) {
var unicode = e.keyCode;
if (unicode == 49 || unicode == 50 || unicode == 51 || unicode == 52 || unicode == 53 || unicode == 54 || unicode == 55 || unicode == 56 || unicode == 57 || unicode == 48) {
return true;
} else {
return false;
}
// Only enter the minus sign (-) if the user enters it first
if (unicode == 45 && input.value == "") {
return true;
}
};
</script>
I'd suggest:
var input = document.getElementById("myInput");
input.onkeypress = function(e) {
switch (e.keyCode){
case 45:
return this.value.length == 0 ? true : false;
break;
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return true;
break;
default:
return false;
break;
}
};
JS Fiddle demo.
The reason your original code failed is simply that you'd already returned from the function before the if condition could be assessed. In this version if the - key is pressed a ternary returns true if there is no current value (so the - will be the first character), or false if there is already a value (and therefore the - will not be the first character).
Order of opperations, you are returning false on the 0-9 before you are ever asking about the minus sign. move the minus sign if block above the 0-9 if block and you are golden
<input type="text" maxlength="10" id="myInput">
<script>
var input = document.getElementById("myInput");
input.onkeypress = function(e) {
var unicode = e.keyCode;
// Only enter the minus sign (-) if the user enters it first
if (unicode == 45 && input.value == "") {
return true;
}
if (unicode == 49 || unicode == 50 || unicode == 51 || unicode == 52 || unicode == 53 || unicode == 54 || unicode == 55 || unicode == 56 || unicode == 57 || unicode == 48) {
return true;
} else {
return false;
}
};
</script>
keyCode is the wrong property in all browsers except IE. You need charCode or which in other browsers. Using this you'll get character code instead and can use a regular expression to test the typed character. You also need to allow non-printable keypresses such as delete, backspace and arrow keys in browsers that fire keypress events for such keys.
Demo: http://jsfiddle.net/7XLqQ/3/
var input = document.getElementById("myInput");
input.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */ ) {
return;
}
var typedChar = String.fromCharCode(charCode);
// Allow numeric characters
if (/\d/.test(typedChar)) {
return;
}
// Allow the minus sign (-) if the user enters it first
if (typedChar == "-" && this.value == "") {
return;
}
// In all other cases, suppress the event
return false;
};
There is one case that isn't considered here, which is when the user places the caret at the start of the input and types a minus sign. For that, you'd need to detect the caret position. Here's some cross-browser code to detect whether the caret is at the start of the input, adapted from this answer:
function isCaretAtTheStart(el) {
if (typeof el.selectionEnd == "number") {
// Modern browsers
return el.selectionEnd == 0;
} else if (document.selection) {
// IE < 9
var selRange = document.selection.createRange();
if (selRange && selRange.parentElement() == el) {
// Create a working TextRange that lives only in the input
var range = el.createTextRange();
range.moveToBookmark(selRange.getBookmark());
return range.moveEnd("character", -el.value.length) == 0;
}
}
return false;
}
Here's a revised demo: http://jsfiddle.net/7XLqQ/5/
Finally, my favourite resource on JavaScript key events, which will tell you everything you need to know: http://unixpapa.com/js/key.html
I'd suggest:
$(".class_name").keypress(function (e) {
if (e.which != 8 && e.which != 0 && e.which != 45 && (e.which < 48 || e.which > 57)) {
return false;
}
});

Categories

Resources