I have a string. I want to allow for upper case letters, lower case letters, numbers, and these special characters: !$/%##.
I would expect this to pass: abcABC123!
I would expect this to fail: abcABC123*
I have tried the following code:
var myString = 'abcABC123*'
// var myString = 'abcABC123!'
if (myString.match(/^[a-zA-Z0-9]!\$\/%##/)) {
alert('this works!');
} else {
alert('Invalid Character');
}
As the code sits now, I always hit the else statement. Be gentle I am not a RegEx expert, or an expert of any kind for that matter.
Note: I would appreciate a pure JavaScript Solution.
Check the snippet, change the regEx pattern to ^[a-zA-Z0-9!%##]+$/g so this could easily work
var myString = 'abcABC123%'
// var myString = 'abcABC123!'
if (myString.match(/^[a-zA-Z0-9!\%\$##]+$/g )) {
alert('this works!');
} else {
alert('Invalid Character in your password');
}
Add those characters to the character set and use $ for asserting position at end of string:
^[A-Za-z0-9!$/%##]+$
Check the regex here.
Snippet:
var myString = 'abcABC123!'
if (myString.match(/^[A-Za-z0-9!$/%##]+$/)) {
console.log('this works!');
} else {
console.log('Invalid Character');
}
Check a live JavaScript fiddle here.
Related
I've searched a lot questions to find a way to a Regex that matches a whole word only. I came up with several answers and questions but a lot of them are not what I need.
For example one of the best rated question on SO shows up with this solution:
let regx = new RegExp( "(^|\s)element-pattern(?=\s|$)" );
let text = "element-pattern";
if(text.match(regx)) {
console.log("in it");
}
text = "element-pattern has-variations";
if(text.match(regx)) {
console.log("in it");
} else {
console.log("not in");
}
The problem I have is that it matches too good for me. In my example the second statement should also be true. What can I change on my RegEx so that it don't fails the second time?
I think the issue is that you are creating a RegExp object from a string. When you use backslash (\) in a regular JS string, it is interpreted as an escape character, so \s becomes just s. Use a RegExp literal instead. You could also just escape the backslashes like new RegExp( "(^|\\s)element-pattern(?=\\s|$)" ), but I prefer the literal notation.
let regx = /(^|\s)element-pattern(?=\s|$)/
let text = "element-pattern";
if(text.match(regx)) {
console.log("in it");
}
text = "element-pattern has-variations";
if(text.match(regx)) {
console.log("in it");
} else {
console.log("not in");
}
I am writing a function which takes string as an argument. Then if the string begins with capital letter then return true otherwise return false. But my current function only works for one word string which I want it to work for both one word and a whole sentence. How can I improve my code to achieve this? Secondly, it should not work when numbers are passed inside sentence. How can I do this?
Here is my code
function takeString (str) {
var regex = /^[A-Za-z]+$/;
if (str.match(regex)) {
if (str.charAt(0) === str.toUpperCase().charAt(0)) {
alert('true');
return true;
} else {
alert('false');
return false;
}
} else {
alert('Only letters please.');
}
}
takeString('This is'); // shows Only letters please which is wrong. this should work
takeString('String); // returns true which right
takeString('string'); // returns false which is right
takeString('This is 12312321'); // shows only letters please which is right bcoz it has digits
takeString('12312312'); // show Only letters please which is right.
Spaces aren't letters. You have to add them into your character set:
> 'This is a string'.match(/^[A-Za-z]+$/);
null
> 'This is a string'.match(/^[A-Za-z\s]+$/);
["This is a string"]
\s matches all whitespace, so if you don't want to match tabs, replace \s with a space.
Here's a slightly more condensed version of your code:
function takeString(str) {
return str.match(/^[A-Z][A-Za-z ]*$/);
}
along with the regex advice given by Blender, you'll want to also do the following (in order to satisfy the need to check each word ... assuming words are space or tab separated only:
use the split function to break the string into words ( var mywords = str.split(/\s+/) )
iterate over mywords array returned by split, checking each array element against the regex
return an error if the regex doesnt match
return success if you match every word
takeString (str) {
var mywords = str.split(/\s+/);
for (i = 0; i < mywords.length; i++) {
if (str.match(/^[A-Z][A-Za-z]*$/) != true) {
return false;
}
}
return true;
}
(someone needs to check my js ... )
I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < chkfile.value.length; i++)
{
if (iChars.indexOf(chkfile.value.charAt(i)) != -1)
{
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
Suppose I want to upload a file desktop.zip from any Linux/Windows machine.
The value of chkfile.value is desktop.zip in Firefox, but in Chrome the value of chkfile.value is c://fakepath/desktop.zip. How do I get rid of c://fakepath/ from chkfile.value?
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Try This one.
function containsSpecialCharacters(str){
var regex = /[ !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
return regex.test(str);
}
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
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/
I am trying to make a function that checks for special characters such as !##$%^&*~ when I input a password. I've been using regular expressions to check for everything else, but does anyone know how I can make it so the function checks the password for at least one of these special characters?
Here's what I have:
function validateEmail(email)
{
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
return emailPattern.test(email);
}
function validatePassword(password)
{
var passwordPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])./;
return passwordPattern.test(password)
}
function validate()
{
var email = user.email.value;
if(validateEmail(user.email.value))
user.validEmail.value = "OK";
else
user.validEmail.value = "X";
if(validatePassword(user.password.value))
user.validPassword.value = "OK";
else
user.validPassword.value = "X";
}
You can match any non-(letters, digits, and underscores) characters with \W.
So to check the password if has any special character you can just simply use:
if (password.match(/\W/)) {
alert('you have at least one special character');
}
to use it in your function you can replace the whole regex with:
var passwordPattern = /^[\w\W]*\W[\w\W]*$/;
that will return true if the string has at least one special character.