Regex which should not allow any special characters except , - javascript

I am trying to create a regular expression which does not allow any special characters except ,, . and they should not come side by side.
For example: STax.sdn,skm should be accepted whereas SDs,.Hnj should throw an error message. I have used the below code, however it is accepting , and . side by side which I don't want.
function validateAnnouncementTags(){
var announcementTags = document.getElementById("announcementTags").value;
if (announcementTags.search(/[<>'+\"\/`\\\[\]^={}%;##!$&*()?:|]/)>-1 ) {
$('#announcementTagsSpecialCharError').addClass('show');
} else {
$('#announcementTagsSpecialCharError').addClass('hide');
$('#announcementTagsSpecialCharError').removeClass('show');
}
}

use this pattern:
/^(?!.*[\.,])/

Based on your comments, I am assuming that you want to accept any letters separated by periods or commas. How about we:
Check for valid characters, and
Ensure that no "special" chars occur adjacent?
we can use
function validateAnnouncementTags() {
var announcementTags=document.getElementById("announcementTags").value;
if (announcementTags.match(/[a-zA-Z\.,]*/)[0] != annoucementTags
|| announcementTags.search(/[\.,][\.,]/) >= 0
) {
$('#announcementTagsSpecialCharError').addClass('show');
} else {
$('#announcementTagsSpecialCharError').addClass('hide');
$('#announcementTagsSpecialCharError').removeClass('show');
}
}
But, if I may be so bold as to assume more structure to your acceptable syntax:
Accept any sequence of letters separated by a comma or period
The sequence will not start with a comma or period
The sequence can end with a comma or period
Then we can use:
function validateAnnouncementTags() {
var announcementTags=document.getElementById("announcementTags").value;
if (announcementTags.match(/([a-z0-9]+[\.,]?)*/)[0] != annoucementTags ) {
$('#announcementTagsSpecialCharError').addClass('show');
} else {
$('#announcementTagsSpecialCharError').addClass('hide');
$('#announcementTagsSpecialCharError').removeClass('show');
}
}

Related

Javascript remove all characters by regex rules

Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.

Why am I getting 'Uncaught TypeError: regex.test is not a function' when used inside another function?

I may just be being thick here but I don't understand why I am receiving this error. Outside of the function the .test() works fine. But inside, I get the error. Was thinking it was something to do with the scope of the .test() function but am I just missing something blindingly obvious here?
function cFunctionfirst() {
firstField = document.getElementById("sname_input_first").value;
document.getElementById("demo").innerHTML = "first: " + firstField;
console.log(firstField);
var regex = "!##$£%^&*()+=[]\\\';,./{}|\":<>?";
if(regex.test(firstField)){
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
That's because regex is not a RegExp object, but just a string. It should be declared as such (remember to escape special characters using \):
var regex = /[!##\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
Not only have I escaped some special regex characters, but you will need to wrap the entire selection inside unescaped [ and ] brackets, so that you test against a set of characters.
p/s: These are the set characters that need to be escaped: \ ^ $ * + ? . ( ) | { } [ ]
See proof-of-concept example:
function cFunctionfirst(value) {
var regex = /[!##\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
if(regex.test(value)){
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
cFunctionfirst('Legal string');
cFunctionfirst('Illegal string #$%');
Alternatively, if you don't want to manually escape the characters, you can either use a utility method to do it, or use an ES6 non-regex approach, which is probably a lot less efficient: checkout the JSPerf test I have made. Simply add the blacklisted characters literally in a string, split it, and then use Array.prototype.some to check if the incoming string contains any of the blacklisted characters:
function cFunctionfirst(value) {
var blacklist = '!##$£%^&*()+=[]\\\';,./{}|":<>?'.split('');
if (blacklist.some(char => value.includes(char))) {
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
cFunctionfirst('Legal string');
cFunctionfirst('Illegal string #$%');

Writing a regex expression for special characters in JavaScript

I know my code is wrong, I am trying to test for certain characters, and as long as they exist for each char in the input field, it will pass true, otherwise pass false.
function isChar(value) {
//Trying to create a regex that allows only Letters, Numbers, and the following special characters # . - ( ) # _
if (!value.toString().match(/#.-()#_$/)) {
return false;
} return true;
}
Assuming you're actually passing a character (you don't show how this is called), this should work:
function isChar(value) {
if (!value.toString().match(/[a-z0-9#.\-()#_\$]/i)) {
return false;
} else
return true;
}
console.log(isChar('%')); // false
console.log(isChar('$')); // true
console.log(isChar('a')); // true
If instead you're passing a string, and wanting to know if all the characters in the string are in this "special" list, you'll want this:
function isChar(value) {
if (! value.match(/^[a-z0-9#.\-()#_\$]*$/i)) {
return false;
} else
return true;
}
console.log(isChar("%$_")); // false
console.log(isChar("a$_")); // true
Characters that have meaning in regexp need to be escaped with \. So for example you would replace $ with \$ and so on for the other such characters. So the final regexp would look like:
#.\-()#_\$
Since you need to escape both the - and the $.
The \w class will catch the alpha numeric. The rest you provided (but properly escaped):
function isChar(value) {
return value.toString().match(/[\w#.\-()#_\$]/) ? true : false
}

Checking for invalid characters from an input with jQuerys

I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.
Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters
Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.
This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}
If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Regular expression for upper case letter only in JavaScript

How can I validate a field only with upper case letters which are alphabetic. So, I want to match any word made of A-Z characters only.
Try something like this for the javascript validation:
if (value.match(/^[A-Z]*$/)) {
// matches
} else {
// doesn't match
}
And for validation on the server side in php:
if (preg_match("/^[A-Z]*$/", $value)) {
// matches
} else {
// doesn't match
}
It's always a good idea to do an additional server side check, since javascript checks can be easily bypassed.
var str = 'ALPHA';
if(/^[A-Z]*$/.test(str))
alert('Passed');
else
alert('Failed');
Try this:
if (<value>.match(/^[A-Z]*$/)) {
// action if is all uppercase (no lower case and number)
} else {
// else
}
here is a fiddle: http://jsfiddle.net/WWhLD/

Categories

Resources