jQuery: Check if special characters exists in string - javascript

I know this question is asked more often here on Stack, but I can't seem to get a straight answer out of the questions already posted.
I need to check if all special characters (except -) are in a string, if so, then give the user an alert.
What I have so far is this:
if($('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('$') == -1 || $('#Search').val().indexOf('%') == -1 || $('#Search').val().indexOf('^') == -1 || $('#Search').val().indexOf('&') == -1 || $('#Search').val().indexOf('*') == -1 || $('#Search').val().indexOf('(') == -1 || $('#Search').val().indexOf(')') == -1 || $('#Search').val().indexOf('_') == -1 || $('#Search').val().indexOf('\'') == -1 || $('#Search').val().indexOf('\"') == -1 || $('#Search').val().indexOf('\\') == -1 || $('#Search').val().indexOf('|') == -1 || $('#Search').val().indexOf('?') == -1 || $('#Search').val().indexOf('/') == -1 || $('#Search').val().indexOf(':') == -1 || $('#Search').val().indexOf(';') == -1 || $('#Search').val().indexOf('!') == -1 || $('#Search').val().indexOf('~') == -1 || $('#Search').val().indexOf('`') == -1 || $('#Search').val().indexOf(',') == -1 || $('#Search').val().indexOf('.') == -1 || $('#Search').val().indexOf('<') == -1 || $('#Search').val().indexOf('>') == -1 || $('#Search').val().indexOf('{') == -1 || $('#Search').val().indexOf('}') == -1 || $('#Search').val().indexOf('[') == -1 || $('#Search').val().indexOf(']') == -1 || $('#Search').val().indexOf('+') == -1 || $('#Search').val().indexOf('=') == -1)
{
// Code that needs to execute when none of the above is in the string
}
else
{
alert('Your search string contains illegal characters.');
}
But this doesn't seem to work. Can anyone help me on this matter?

If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.

var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
for(i = 0; i < specialChars.length;i++){
if(string.indexOf(specialChars[i]) > -1){
return true
}
}
return false;
}
if(check($('#Search').val()) == false){
// Code that needs to execute when none of the above is in the string
}else{
alert('Your search string contains illegal characters.');
}

You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

You are checking whether the string contains all illegal characters. Change the ||s to &&s.

Related

Improving if-else with multiple values?

Is there a better way to do this?
if(cpf.length !== 11 || cpf === "00000000000" || cpf === "11111111111" ||
cpf === "22222222222" || cpf === "33333333333" || cpf === "44444444444" ||
cpf === "55555555555" || cpf === "66666666666" || cpf === "77777777777" ||
cpf === "88888888888" || cpf === "99999999999"){
You could debate if this is better but this is what I like to do in that sort of situation:
// Name this something relevant to the problem
var possibleValues = ["0000000000", ...];
if (possibleValues.includes(cpf)) {
// do stuff
}
or if you're in an environment that doesn't have includes
if (possibleValues.indexOf(cpf) > -1) {
// do stuff
}
Another possibility is using a regular expression:
if (cpf.length === 11 && cpf.match(/^(\d)\1+$/)) {
// do stuff
}
^: Start at the beginning
(\d): Look for a digit and remember it
\1+: Look for the remembered digit repeatedly
$: Hit the end of the string
Using indexOf Something like
var possibleValues = [ "00000000000", "1111111111" ]; //add more values
if ( cpf.length != 11 || possibleValues.indexOf( cpf ) != -1 )
{
//value matching
}
Alternative Ecmascript5 solution using isNaN() and RegExp.text() functions:
if (cpf.length !== 11 || (!isNaN(f = cpf[0]) && new RegExp("^"+ f + "{11}$").test(cpf))) {
// do something
}
isNaN() - to check if we have only numbers(at start)
new RegExp("^"+ f + "{11}$").test(cpf) - to test if we have a sequence of same 11 digits

Check for 4 numbers before decimal and 1 number after decimal

I have an input number field which should allow max 4 numbers before decimal and max 1 number after decimal or upto 6 numbers without decimal.
E.g. Valid 1.2, 113.5, 1234.5, 456789.
I used this RegEx ^\d{0,4}\.?(\.\d{0,1})?$ on keypress. It works fine, but gives false only after displaying the number like 113.55. How can I solve this?
My Keypress Function:
function OnKeyPress(e,DivID) {
if ( e.which != 8 && e.which != 0 && e.which != 13 && e.which != 46 && (e.which < 48 || e.which > 57)) {
return false;
}
var val = j$('[id$='+DivID+']').val();
if(DivID == 'ProximityCPPercentage')
{
var x = event.which || event.keyCode;
if(val.indexOf('.') >= 0 && e.which == 46)
return false;
else if(e.which == 46 && val.length == 3)
return false;
if(val.indexOf('.') == 0)
val = '0' + val;
if(e.which != 46)
{
strval = val + String.fromCharCode(x);
var re = /^((.|0|[1-9]\d?)(\.\d{1})?|100(\.0?)?)$/;
if(!re.test(strval))
return false;
}
}
else if(val.indexOf('.') > 0)
{
if(e.which == 46 )
return false;
var arra = val.split('.');
var decval = arra[1];
var val = arra[0];
if(val.length > 6)
return false;
if(decval.length > 0)
return false;
}
else if(e.which != 46 )
{
if(val.length > 5)
return false;
}
}
Use following regex
^\d{0,4}([.\d]\d)?$
Regex explanation here
If you don't want to match 5 digits then use negative look-ahead assertion to avoid that
^(?!\d{5}$)\d{0,4}([.\d]\d)?$
Regex explanation here
/^(?:\d{0,4}\.?(\d)|\d{0,6})?$/
NOTE: This also matches .2 and 12345 and '' (empty string). Based on your question, its not clear if you want to exclude those.
Explanation:
^ Start the line.
(?: Start a "non-capturing group".
\d{0,4} Between 0 and four digits.
\.? Zero or one literal dots.
(\d) Capture one digit. (Do you want this captured?)
| OR
\d{0,6} Zero or Six digits.
) Closes our non-capturing group (number 2).
$ End the line.
Tests:
var reg_exp = /^(?:\d{0,4}\.?(\d)|\d{0,6})?$/;
[
'1.2',
'113.5',
'1234.5',
'456789',
'12345',
'.2',
'',
'1234.',
'113.55'
].forEach(c => {
console.log('"' + c + '" tests to "' + reg_exp.test(c) + '"');
});
// "1.2" tests to "true"
// "113.5" tests to "true"
// "1234.5" tests to "true"
// "456789" tests to "true"
// "12345" tests to "true"
// ".2" tests to "true"
// "" tests to "true"
// "1234." tests to "false"
// "113.55" tests to "false"

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

Input only with correct numeric

i wanted to ask how i can combine my regex with the if( ( !regex.test( sybol.... condition, if there is a possibility, and also, how I can shorten my code? without loosing good code view. Also, dash can be only in first place and only one in input, and the same with dot.
$( this ).bind( 'keypress', function( e ){
var code = e.keyCode || e.which;
var symbol = String.fromCharCode( code );
var regex = /[-0-9]|[\b]/;
var currVal = $( this ).val();
var insideInput = currVal.indexOf( '-' );
if( ( !regex.test( symbol ) && code != 37 && code != 39 && code != 46 ) ||
( code == 45 && insideInput == 0 ) || ( currVal.length != 0 && code == 45 ) ) {
e.preventDefault();
}
});
If you want digits only input, you can use following:
$('#test').on('input', function() {
var oldVal = $(this).val();
// remove everything but digits
var newVal = oldVal.replace(/[^\d]/g, '');
// put leading minus back in place (if there was one)
if(oldVal.trim().length > 0 && oldVal.trim()[0] == '-') {
newVal = '-' + newVal;
}
$(this).val(newVal);
});​
See this DEMO.
If you want more, please update your question (describe what are you trying to achieve with your script).
So i combined Michal Klouda ideas and mines and done this function:
$('input').bind('keypress paste', function(e) {
var currVal = $(this).val();
var code = e.keyCode || e.which;
var symbol = String.fromCharCode( code );
var regex = /[0-9\-]|[\b]/;
if(
!regex.test( symbol ) && code != 37 && code != 39 && code != 46 ||
symbol == '%' ||
currVal.length > 0 && currVal[0] == '-' && symbol == '-' ||
currVal.length > 0 && symbol == '.' && currVal.indexOf( '.' ) > -1 ||
currVal.length < 1 && symbol == '.' ||
currVal.length < 2 && symbol == '.' && currVal[0] == '-'
){
e.preventDefault();
}
});
Some explanations:
regex = /[0-9\-]|[\b]/;
Removes all non numeric, exept dash, %, backspace symbols.
Why it isn't removing % symbol, i can't find. ( one more place to inprove code )
code != 37 // leaves left arrow
code != 39 // leaves right arrow
code != 46 // allows to delete code with delete button
symbol == % // prevents from percentage symbol
Other conditions allow you to write one dot and one dash symbol.
Dash allowed only in first place, dot allowed in two conditions: with dash or without.
With dash allowed from 3 position, without from 2 position, but only once. Also it prevents user to paste the code from clipboard.
CODE TESTED:
IE7+
FF
Chrome
Safari
Opera
Try DEMO
P.S: thanks Michal Klouda for help.

Categories

Resources