Matching special characters and letters in regex - javascript

I am trying to validate a string, that should contain letters numbers and special characters &-._ only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
While using the above code, the string abc&* is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._ comes, the string should evaluate as invalid. How can I do that with a regex?

Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/

Well, why not just add them to your existing character class?
var pattern = /[a-zA-Z0-9&._-]/
If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:
var pattern = /^[a-zA-Z0-9&._-]+$/
The added ^ and $ match the beginning and end of the string respectively.
Testing for letters, numbers or underscore can be done with \w which shortens your expression:
var pattern = /^[\w&.-]+$/
As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:
if (pattern.test(qry)) {
// qry is non-empty and only contains letters, numbers or special characters.
}
Update 2
In case I have misread the question, the below will check if all three separate conditions are met.
if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
// qry contains at least one letter, one number and one special character
}

Try this regex:
/^[\w&.-]+$/
Also you can use test.
if ( pattern.test( qry ) ) {
// valid
}

let pattern = /^(?=.*[0-9])(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!##$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123#"); //true as it contains all the above

I tried a bunch of these but none of them worked for all of my tests. So I found this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$
from this source: https://www.w3resource.com/javascript/form/password-validation.php

Try this RegEx: Matching special charecters which we use in paragraphs and alphabets
Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)
.test(str) returns boolean value if matched true and not matched false
c# : ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$

Here you can match with special char:
function containsSpecialChars(str) {
const specialChars = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
return specialChars.test(str);
}
console.log(containsSpecialChars('hello!')); // 👉️ true
console.log(containsSpecialChars('abc')); // 👉️ false
console.log(containsSpecialChars('one two')); // 👉️ false

Related

Javascript validation to allow only string followed by number

I want to restrict the user to enter in textbox only string followed by number only for e.g
AA1->true
AA1A->False
AA12->True
AB12AA14AB->false
12AA->false
ABC12->false
AA->false
So please let me know how can I add validation for above condition/cases using javascript.
Use a regular expression:
const validate = str => /^[A-Z]+\d+$/.test(str);
`AA1
AA1A
AA12
AB12AA14AB
12AA
ABC12
AA`
.split('\n')
.forEach(str => console.log(validate(str)));
^ indicates the start of the string, [A-Z]+ matches one or more uppercase alphabetical characters, \d+ matches one or more numbers, and $ matches the end of the string.
function isStrEndWithNum(str){
if(str)
return !isNaN(str[str.length-1]);
return false;
}
You can use the .test function which is present in JavaScript
/^([\w]+[0-9])$/.test('YourStringHere');
i am just confused with second last condition of yours.
Other than that all your conditions are passed with the above code.

Allowed Characters Regex (JavaScript)

I'm trying to build a regex which allows the following characters:
A-Z
a-z
1234567890
!##$%&*()_-+={[}]|\:;"'<,>.?/~`
All other characters are invalid. This is the regex I built, but it is not working as I expect it to. I expect the .test() to return false when an invalid character is present:
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*/g
return regex.test(string);
}
In this case, the test is always returning "true", even when "^" is present in the string.
Your regex only checks that at least one of the allowed characters is present. Add start and end anchors to your regex - /^...$/
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g
return regex.test(string);
}
... another approach, is instead of checking all characters are good, to look for a bad character, which is more efficient as you can stop looking as soon as you find one...
// return true if string does not (`!`) match a character that is not (`^`) in the set...
return !/[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/.test()
Instead of searching allowed characters search forbidden ones.
var string = 'abcd^wyd';
function regTest (string) {//[^ == not
var regex = /[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/g
return !regex.test(string);//false if found
}
console.log(regTest(string));
The regex, as you've written is checking for the existence of the characters in the input string, regardless of where it appears.
Instead you need to anchor your regex so that it checks the entire string.
By adding ^ and $, you are instructing your regex to match only the allowed characters for the entire string, rather than any subsection.
function isValidPassword (pwd) {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g\;
return regex.test(pwd);
}
alert(isValidPassword('abcd^wyd'));
Your regexp is matching the first part of o=your string i.e. "abcd" so it is true . You need to anchor it to the start (using ^ at the beginning) and the end of the string (using $ at the end) so your regexp should look like:
^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]$
That way it will need to match the entire string.
You can visualize it in the following link:
regexper_diagram
This regex will work.
var str = 'eefdooasdc23432423!##$%&*()_-+={[}]|:;"\'<,>.?/~\`';
var reg = /.|\d|!|#|#|\$|%|&|\*|\(|\)|_|-|\+|=|{|\[|}|]|\||:|;|"|'|<|,|>|\.|\?|\/|~|`/gi;
// test it.
reg.test(str); //true
I use this site to test my regex.
Regex 101

validate string which has only one special character using javascript

I know there are several question like this on Stack-overflow, but I can't seem to get a straight answer out of the questions already posted.Looking forward if someone can help me.
I want to validate a string & return TRUE if it satisfies below condition
String contains only one special character i.e _ (underscore)
& this special character should not appear at beginning or end of the string
Example:
var demo1="23dsfXXXa32_XXXX" // Valid, should returns TRUE
var demo2="_23dsfXXXa32_XXXX" // Invalid,should returns FALSE
var demo3= "23dsfXXXa32XXXX_" //invalid,should returns FALSE
var demo4= "_" //invalid,should returns FALSE
var demo5= "&sdfsa_XX";// returns false
Tried: FIDDLE
if(/^[a-zA-Z0-9_ ]*$/.test(demo1) == true) {
alert('Valid String');
}
Result: Not functioning as per expected
Since you've said you require that the character be there, one way is to do it with a regular expression is with a negated character class at each end with a non-negated one in the middle:
var rex = /^[^_]+[_][^_]+$/;
That only handle underscores; add other "special" characters to all three character classes there.
How that works:
^ matches start of string
[^_]+ requires one or more characters not in the class
[_] requires exactly one character in the class
[^_]+ requires one or more characters not in the class
$ matches end of string
You could simplify it by using indexOf to verify that its not in the first or last position and split to see if its there only once. This is usually faster than a regex pattern.
function checkString(str){
return str.indexOf("_") !== 0 && str.indexOf("_") !== str.length-1 && str.split("_") === 2;
}

Regular Expression - followed by

How can I write a regex that match this
123/456
123/456/?
but not this
123/456/
I want on the second / it must be followed by a ?.
For Example I would like it to match this
'123/456'.match(X) // return ['123/456']
'123/456/?'.match(X) // return ['123/456/?']
'123/456/'.match(X) // return null
Update
I missed to say one important thing. It must not end with '?', a string like '123/456/?hi' should also match
You can try this regex: \d{3}/\d{3}(/\?.*)?
It will match
3 digits
followed by a /
followed by 3 digits
followed by /?any_text (e.g. /?hi) (optional)
This example uses regular expression anchors like ^ and $, but they are not required if you only try to match against the target string.
var result = '123/456/?hi'.match(/\d{3}\/\d{3}(\/\?.*)?/);
if (result) {
document.write(result[0]);
}
else {
document.write('no match');
}
This regular expression will work /^\d{3}\/\d{3}(\/\?.*)?/
See this JSFiddle.
Note: if you think it should match any number of digits then use \d+ instead of \d{3}. The later matches exactly 3 digits.
Here you are:
[0-9]+/[0-9]+(/\?[^ ]*)?
What other rules do you have?
If you want to accept all strings with last character other than ?, use "[^?]$"
If you want to accept strings that start with 123/456 and optionally end with /?, use "^123/456(/\?)?$"
I think this should work:
'123/456'.match(/^123\/456(\/\?)?$/) // returns ["123/456", undefined]
'123/456/'.match(/^123\/456(\/\?)?$/) // returns null
'123/456/?'.match(/^123\/456(\/\?)?$/) // returns ["123/456/?", "/?"]
EDIT: added the other cases

Find out if a string is made up with a certain set of characters

How can I out if a string only contains a certain set of characters: { A-Z and } ?
For example
{VARIABLE} => should return true
{VARiABLE} => should be false, because there's a lowercase i inside
{ VARIABLE} => should be false because there's a space etc.
Oh, very important:
the string MUST have at least one character between { and }, so:
{} should be false too...
In that case use:
/^{[A-Z]+}$/.test(str);
The regexp represents any string of the format:
First a {
Then one or more capital letters
Then a }
The ^...$ makes sure that the string should be exactly of this form, rather than a substring only (otherwise test{AAA} would match too).
This sounds like a good case to use regular expressions. In particular, regexes allow one to match a range of characters - [A-Z{}] would match any character which is either an uppercase letter, {, or }.
EDIT based on new requirements - you want to match something that starts with a literal {, then has at least one character in the range A-Z, then a closing }. Which gives the regex:
{[A-Z]+}
Thus you could match against the entire regex:
val input = "{VARIABLE}"
return input.test(/{[A-Z]+}/) // returns true
"{VARiABLE}".test(/{[A-Z]+}/) // returns false
"{ VARIABLE}".test(/{[A-Z]+}/) // returns false
"".test(/{[A-Z]+}/) // returns false - open bracket didn't match
"{}".test(/{[A-Z]+}/) // returns false - A-Z part didn't match
Use this regex: ^[A-Z{}]+$. It allows only A-Z and {}
Do a negative regex match. If you match something like /[^A-Z{}]/ and get a success, then the string contains something that's "not allowed".
Try this regex...
/^[{}A-Z]+$/
/^[{}A-Z]+$/.test("{VARIABLE}") // => true
Use this expression.
[A-Z{}]*
Here the square brackets [] insist on what characters to be present and * says that this patter can repeat multiple times.
Jquery Code:
$(document).ready( function(){
$('#test_regex').click( function(){
regex= /^{[A-Z]+}$/;
str= $('#reginput').val();
result= regex.test(str);
if( result ){
alert("It's the correct value, yes it's right");
}else{
alert("It's incorrect value.. You know");
}
});
});
HTML Code:
<input type="text" id="reginput"/>
<button id="test_regex">Check Value</button>
It will return alert("It's the correct value, yes it's right"), if value is {UPPERCASELETTERS}

Categories