In our project, we use this regular expression to validate emails:
"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,7}|[0-9]{1,3})(\]?)$"
But it allows non English characters.
For example:
"مستخدم#mail.com"
"userمحمد#mail.com"
"userName#خادم.com"
are valid emails.
How to add another rule to this expression to limit inputs to English letters only?
You can omit the alternation | in your pattern, and there is an optional closing bracket \]? which I think you don't need in an email address.
This part in the regex with Javascript and C# [\w-\.] does not seem to be a valid range in a character.
Instead of using \w you can use [A-Za-z0-9] to match ASCII chars and digits 0-9 in C#.
If you don't want to match consecutive dots or hyphens, you can use a pattern like this and then extend it if you have more characters that you want to allow:
^[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*#[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*\.[a-z]{2,}$
Regex demo
Note that this only validates an email address of this format.
Can do like this
string[] StrInputNumber = { "pradeep1234#yahoo.in", "مستخدم#mail.com'", "userمحمد#mail.com", "userName#خادم.com" };
Regex ASCIILettersOnly = new Regex(#"^[\P{L}A-Za-z]*$");
foreach (String item in StrInputNumber) {
if (ASCIILettersOnly.IsMatch(item)) {
Console.WriteLine(item + " ==> valid");
}
else {
Console.WriteLine(item + " ==>not valid");
}
}
Output
for some basic explanation about regex Click Here
You can use this website to test your regular expression
If you don't need to keep your current expression you can use this one instead:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.
I tested it with your examples and it works as you want.
Related
I want a regex for alphanumeric characters in angularJS, I've tried some regex like "(\d[a-z])" but they allow me to enter only number as well as only alphabets. But I want a regex which won't allow me to enter them.
Example:
121232, abchfe, abd()*, 42232^5$ are some example of invalid input.
12fUgdf, dGgs1s23 are some valid inputs.
This one requires atleast one of each (a-z, A-Z and 0-9):
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]+)$
You can try this one. this expression satisfied at least one number and one character and no other special characters
^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$
in angular can test like:
$scope.str = '12fUgdf';
var pattern = new RegExp('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$');
$scope.testResult = pattern.test($scope.str);
PLUNKER DEMO
If you wanted to return a replaced result, then this would work:
var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi,'');
console.log(b);
This would return:
Test123TEST
OR
/^([a-zA-Z0-9 _-]+)$/
the above regex allows spaces in side a string and restrict special characters.It Only allows a-z, A-Z, 0-9, Space, Underscore and dash.
try this one : ^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$
dGgs1s23-valid
12fUgdf-valid,
121232-invalid,
abchfe-in valid,
abd()*- invalid,
42232^5$- invalid
I'm attempting to validate a field name to match a certain format in JavaScript using Regular Expressions.
I need the string inputted to resemble this:
word\word\word
So anything inputted can't be blank, and it must be three words seperated by a backslash.
This is the code i'm working with, but i'm not sure if the pattern is the right syntax?!!
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/[a-Z|/\\/|a-Z|/\\/|a-Z\s]/;
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
}
else
{
alert("match");
}
}
Any help will be very appreciated!!!
If by word you mean the English letters a-z in upper or lower case, then:
/^(?:[a-z]+\\){2}[a-z]+$/i
That says:
^ Beginning of string
(?:...) Non-capturing group
[a-z]+ One or more letters a-z (or A-Z because of the i flag at the end). If you also want to allow some other characters, just add them to the [a-z] after the z. If you want to allow hyphens, add \- to it (you need the backslash, depending on where you put the hyphen, so I just always include it). Note that this is very English-centric, and even in English sometimes people write borrowed words with their non-English letters, such as résumé.
\\ Backslash
{2} Repeated twice
(Then another word)
$ End of string
The issues with your expression are:
[a-Z] Is invalid because the range is out of order (Z comes before a). If it were valid (or if you wrote [Z-a]), it would matches everything between Z and a, which isn't just a-z and A-Z
\\/ Requires a backslash and then a slash
| is an alternation (this or that)
\s is whitespace
Try /^[a-z]+\\[a-z]+\\[a-z]+$/
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/^[a-z]+\\[a-z]+\\[a-z]+$/
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
} else {
alert("match");
}
}
If you want to allow the word matching to be case insensitive;
`/^[a-z]+\\[a-z]+\\[a-z]+$/i`
If you want to be a bit more broad with what you define as a 'word', and allow it to consist of alphanumeric characters and underscore;
`/^\w+\\\w+\\\w+$/i`
you can just use this \w+\\\w+\\\w+
or
[a-zA-Z]+(\\[a-zA-Z]+){2}
This should do it
^\w+\\\w+\\\w+$
In javascript
if (/^\w+\\\w+\\\w+$/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
Try this one , See the Regex fiddle for regex demo and Jsfiddle for the code demo
Regex
/(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g
Javascript
function validateResourceName(string) {
var pattern = /(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g;
if (!pattern.test(string)) {
alert("not a match");
} else {
alert("match");
}
}
I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass.
function validText(field)
{
var re = /[a-zA-Z0-9\-\_]$/
if (field.value.search(re) == -1)
{
alert ("Invalid Text");
return false;
}
}
A valid input would be something like
'Valid_Input123'
invalid
'Invalid-Input !'
The \w is a handy regex escape sequence that covers letters, numbers and the underscore character
You should test the entire string for valid characters by anchoring the validity test at the start (^) and end ($) of the expression
The regular expression test method is faster than the string search method
You can also test for one or more characters using the + quantifier
To summarise (in code)
var re = /^\w+$/;
if (!re.test(field.value)) {
alert('Invalid Text');
return false;
}
return true;
Alternatively, you can test for any invalid characters using
/\W/.test(field.value)
\W being any character other than letters, numbers or the underscore character.
Then you might also need to add a length check to invalidate empty strings, eg
if (/\W/.test(field.value) || field.value.length === 0)
You are only testing whether the text ends ($) with one of the characters in the character class. You are also explicitly allowing a dash (\-). If you don't want that, remove it.
Anchor the expression (^, $), add a quantifier (+) and .test whether the string only consists of those characters:
var re = /^[a-zA-Z0-9_]+$/; // or /^\w+$/ as mentioned
if (!re.test(field.value)) {
}
You forgot to anchor your regex at the beginning using ^
test is easier to use
There is no need for the dash.
It should look like this:
if (!/^[a-z0-9_]+$/i.test(field.value)) {
//
}
[\w]* will suffice.
Regex101 Example
This is a very basic Regular Expressions question
Learn more about regular expressions here: regular-expressions.info
I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}
I am working on this code and using "match" function to detect strength of password. how can I detect if string has special characters in it?
if(password.match(/[a-z]+/)) score++;
if(password.match(/[A-Z]+/)) score++;
if(password.match(/[0-9]+/)) score++;
If you mean !##$% and ë as special character you can use:
/[^a-zA-Z ]+/
The ^ means if it is not something like a-z or A-Z or a space.
And if you mean only things like !#$&$ use:
/\W+/
\w matches word characters, \W matching not word characters.
You'll have to whitelist them individually, like so:
if(password.match(/[`~!##\$%\^&\*\(\)\-=_+\\\[\]{}/\?,\.\<\> ...
and so on. Note that you'll have to escape regex control characters with a \.
While less elegant than /[^A-Za-z0-9]+/, this will avoid internationalization issues (e.g., will not automatically whitelist Far Eastern Language characters such as Chinese or Japanese).
you can always negate the character class:
if(password.match(/[^a-z\d]+/i)) {
// password contains characters that are *not*
// a-z, A-Z or 0-9
}
However, I'd suggest using a ready-made script. With the code above, you could just type a bunch of spaces, and get a better score.
Just do what you did above, but create a group for !##$%^&*() etc. Just be sure to escape characters that have meaning in regex, like ^ and ( etc....
EDIT -- I just found this which lists characters that have meaning in regex.
if(password.match(/[^\w\s]/)) score++;
This will match anything that is not alphanumeric or blank space. If whitespaces should match too, just use /[^\w]/.
As it look from your regex, you are calling everything except for alphanumeric a special character. If that is the case, simply do.
if(password.match(/[\W]/)) {
// Contains special character.
}
Anyhow how why don't you combine those three regex into one.
if(password.match(/[\w]+/gi)) {
// Do your stuff.
}
/[^a-zA-Z0-9 ]+/
This will accept only special characters and will not accept a to z & A to Z 0 to 9 digits