Jquery check for alphanumeric charactres - javascript

In the below code Using jquery how to check for only alaphanumeric charaters.Even space and none of the special symbols should be allowed.I do want o use a external plugin
var a='a hjdshj%^& ff234 ./.';
if(var a has special characters)
{
alert('has special characters');
}
EDIT : Even single and double quotes should not be allowed

There is no need of any plugin to check this
you can make use of Regular exprssion to do it easily..
try this
var str='a hjdshj%^& ff234 ./.';
var re = new RegExp(/\$|\/|\^|-/\s,"g");
specialchars = str.match(re);
alert(specialchars.length);

Related

Regular Expression: Allow only characters a-z, A-Z

ExtJS 5.1
Let's say I have an example like that, I want user's name-surname so I don't want any numbers or special chars, I tried so many possibilities but couldn't make it:
var controller=this;
var refs = controller.getReferences();
var exp = '/^([^0-9]*)$/';
onButtonClick: function(button, e, eOpts) {
if(refs.nameSurname.value.match(exp)){
Ext.Msg.alert('ERROR', 'BlaBla');
}
}
With this code, I have no error when i enter a number to text field...
Thank you.
Assuming you need to actually match a string that has no digits...
You should not enclose the regex literal with single quotes, remove them. You do not need the capture group, you can remove ( and ).
Use
var exp = /^[^0-9]*$/;
Now, to check if a string matches a regex, you will be safer using a RegExp#test().
See the demo below:
var refs_nameSurname = "Som8ehere";
if(!(/^[^0-9]*$/.test(refs_nameSurname))){
console.log('ERROR');
}
However, you can reverse the logic, and show an error once a digit is found inside a string (simpler!):
var refs_nameSurname = "Somehere12";
if(/[0-9]/.test(refs_nameSurname)){
console.log('ERROR');
}

javascript regex does not work properly with postal code

'^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$'
the above regular expression accepts inputs like T3K2H3 or T3K-2H3 from .net form but when i run the validation through the javascript; it does not work.
var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$');
var postalCode = 't3k2h3';
var matchesPostalCode = rxPostalCode.exec(postalCode);
if (matchesPostalCode == null || postalCode != matchesPostalCode[0]) {
$scope.AccountInfoForm.PostalCode.$setValidity("pattern", false);
$scope.showLoading = false;
return false;
}
I believe that in javascript, you have to do // instead of ''
as follows:
/^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$/
You might want to check the following link:
Validate email address in JavaScript?
You have two syntaxes to define a regexp object:
var rxPostalCode = /^[abceghj-np-tvxy]\d[abceghj-np-tv-z][ -]?\d[abceghj-np-tv-z]\d$/i;
or
var rxPostalCode = new RegExp('^[abceghj-np-tvxy]\\d[abceghj-np-tv-z][ -]?\\d[abceghj-np-tv-z]\\d$', 'i');
Note that with the second syntax you need to use double backslashes.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
"Do not forget to escape \ itself while using the RegExp("pattern") notation because \ is also an escape character in strings."
var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\\d{1}$');
That should work, I tested it in Chrome's console.
Try the following pattern:
^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz][ -]*\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]\d
Remove the $ at the end and see if that solves your problem.
I also simplified things a bit, the \d{1} is the same as \d
I would also change the [ -]* to [ -]? unless you want to allow multiple spaces or dashes
I suspect what is happening is that the $ expect the end of the line or string, and JavaScript may not store the VAR properly. See if remove the $ solves it, or possibly keeping the $ and trim() the string.

How do I use match() for a white list of characters?

I used preg_match for my server-side validation but I want to have a client side too.
For my PHP I allow those characters:
'/^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/'
How would I make a white list of characters with match() in JavaScript?
EDIT:
I tried this but it didn't work for some reason:
My debugger says, right before the if statement:
218SyntaxError: Invalid regular expression: range out of order in character class
$('#title').blur(function(){
input = $('#title').val();
var invalidChars = /^[^a-z][^a-z\d .:-,!?]+$/i;
if (!invalidChars.test(input)){
alert('true');
}
else {
alert('false');
}
});
all of the above answers are correct, though just a side-note: instead of writing [A-Za-z], a simple /[a-z]/i will suffice. The i is a case-insensitive flag...
var validChars = /^[a-z][a-z\d .:\-,!?]+$/i;
if (validChars.test(myText)){ ... }
Using regex.test(str) is slightly more performant than str.match(regex) if all you want is to know if a match exists or not.
Alternatively, you can early out if you see any invalid character:
var invalidChars = /^[^a-z][^a-z\d .:\-,!?]+$/i;
if (!invalidChars.test(myStr)){
// we passed
}
This allows the regex test to stop the moment it sees a disallowed character.
Try the following
var text = ...;
if (text.match(/^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/)) {
...
}
Actually it's the opposite:
var regexp = /^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/;
if (regexp.test(text)) {
}

jQuery input filter for textarea

I adapted this solution into my script. The idea is to prevent the user from typing unauthorized characters (of course there is also a filter on the back end).
$('#someinput').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
console.log(str);
return '';
}))
})
It works nice, but I also need the users to be able to type specific allowed characters like: .,!?ñáéíóú - I mean, the basic a-zA-Z0-9 plus some basic chars and the whole bunch of special language characters.
What actually needs to be left out are: ##$%^&*()=_+"':;/<>\|{}[]
Any ideas? Thanks!
Solution thanks to Michael
//query
$('#someinput').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
setTimeout(function() {
$('#someinput').val($('#someinput').val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
$('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
},100);
});
Invert your regular expression to only replace the specific characters you want omitted:
$th.val( $th.val().replace(/\s?[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars
Note, a few of them need to be escaped with a backslash inside a [] character class: \\\[\]\^\/
If I'm understanding what you are wanting to do, can't you just add those unwanted characters to your regex instead of doing the [^a-zA-Z0-9]?
Replace that with [##\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]] (notice the escaping)

Remove all special characters with RegExp

I would like a RegExp that will remove all special characters from a string. I am trying something like this but it doesn’t work in IE7, though it works in Firefox.
var specialChars = "!##$^&%*()+=-[]\/{}|:<>?,.";
for (var i = 0; i < specialChars.length; i++) {
stringToReplace = stringToReplace.replace(new RegExp("\\" + specialChars[i], "gi"), "");
}
A detailed description of the RegExp would be helpful as well.
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).
Note that if you still want to exclude a set, including things like slashes and special characters you can do the following:
var outString = sourceString.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
take special note that in order to also include the "minus" character, you need to escape it with a backslash like the latter group. if you don't it will also select 0-9 which is probably undesired.
Plain Javascript regex does not handle Unicode letters.
Do not use [^\w\s], this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.
You really don't want remove these letters together with all the special characters. You have two chances:
Add in your regex all the special characters you don't want remove, for example: [^èéòàùì\w\s].
Have a look at xregexp.com. XRegExp adds base support for Unicode matching via the \p{...} syntax.
var str = "Їжак::: résd,$%& adùf"
var search = XRegExp('([^?<first>\\pL ]+)');
var res = XRegExp.replace(str, search, '',"all");
console.log(res); // returns "Їжак::: resd,adf"
console.log(str.replace(/[^\w\s]/gi, '') ); // returns " rsd adf"
console.log(str.replace(/[^\wèéòàùì\s]/gi, '') ); // returns " résd adùf"
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.js"></script>
using \W or [a-z0-9] regex won't work for non english languages like chinese etc.,
It's better to use all special characters in regex and exclude them from given string
str.replace(/[~`!##$%^&*()+={}\[\];:\'\"<>.,\/\\\?-_]/g, '');
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Їжак). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).
I use RegexBuddy for debbuging my regexes it has almost all languages very usefull. Than copy/paste for the targeted language.
Terrific tool and not very expensive.
So I copy/pasted your regex and your issue is that [,] are special characters in regex, so you need to escape them. So the regex should be : /!##$^&%*()+=-[\x5B\x5D]\/{}|:<>?,./im
str.replace(/\s|[0-9_]|\W|[#$%^&*()]/g, "") I did sth like this.
But there is some people who did it much easier like str.replace(/\W_/g,"");
#Seagull anwser (https://stackoverflow.com/a/26482552/4556619)
looks good but you get undefined string in result when there are some special (turkish) characters. See example below.
let str="bənövşəyi 😟пурпурный İdÖĞ";
i slightly improve it and patch with undefined check.
function removeSpecials(str) {
let lower = str.toLowerCase();
let upper = str.toUpperCase();
let res = "",i=0,n=lower.length,t;
for(i; i<n; ++i) {
if(lower[i] !== upper[i] || lower[i].trim() === ''){
t=str[i];
if(t!==undefined){
res +=t;
}
}
}
return res;
}
text.replace(/[`~!##$%^*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
why dont you do something like:
re = /^[a-z0-9 ]$/i;
var isValid = re.test(yourInput);
to check if your input contain any special char

Categories

Resources