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");
}
}
Related
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.
I am trying to find if a string has valid domain names or not in JavaScript.
As per requirement, these are my valid and invalid domain names.
Valid Domain:
api.google.com
*.api.google.com
*.api.google.user.com
tenant.my.centrify-kibble.net
aws.logs.security.stark.tony.com
myest.r-project.org
login-dev.qacloudad.com
Invalid Domain:
https://google.com
https://www.google.com
https://*.google.com
*.google.com/
*google.com/
*google.com
google.com.
login-dev.qacloudad.com.
login-dev.qacloudad.com.*
.login-dev.qacloudad.com
below code is working as expected for both valid as well as invalid domain except "*google.com".
I am still getting valid expression as result for "*google.com"
How can I fix this RegEx?
var fqdn = "aws.logs.security.stark.tony.com";
if (fqdn.match("^(?!-)[A-Za-z0-9-*]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$")) {
console.log("Matched");
}
else{
console.log("Not Matched");
}
You may use the following pattern:
^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$
Regex demo.
Breakdown:
^ - Beginning of string.
(?:\*\.)? - Match an optional "*." literally.
[a-z0-9]+ - One or more alphanumeric characters.
(?:[\-.][a-z0-9]+)* - A hyphen or a dot followed by one or more alphanumeric characters to be matched zero or more times.
\.[a-z]{2,6} - A dot followed by between two and six letters.
$ - End of string.
JavaScript test:
var fqdn = "aws.logs.security.stark.tony.com";
if (fqdn.match(/^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$/)) {
console.log("Matched");
}
else{
console.log("Not Matched");
}
To support upper-case letters, you can either (re-)add A-Z to the character classes or simply append the i flag at the end:
fqdn.match(/^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$/i)
// ^
I have this regexp
/[A-Za-zÀ-ÿ]+/g
that matches 'words' composed by characters of unlimited lenght.
If I do want to exclude words starting with a capital letter?
I tried
/(^[A-Z])[A-Za-zÀ-ÿ]+/g
but it doesn't seems to work. Can't use things like /w for it doesn't include diacritics.
EDIT: the language in use is Typescript so the javascript engine (which doesn't allow lookbehind, for example) Sorry for not mention this.
EDIT: the input given can be something like
"foo" //should match foo and return true
"Foo" //should not match foo and return false
"fòo" //should match fòo and return true
" " //should not match foo and return false
"." //should not match foo and return false
"," //should not match foo and return false
Code (Typescript) matching without the capital letter thing
isProperWord(word){
/* rejects
- string that are not words (symbols, spaces, etc...)
- names (words starting with a capital letter)
*/
if(word.match(/[A-Za-zÀ-ÿ]+/g)){
return true;
}else{
return false;
}
}
The expression ^[A-Z] means match an uppercase character at the beginning of line. You probably tried to type [^A-Z] which matches a character which is not an uppercase alphabetic between A and Z, but that still doesn't help, because the regex engine will find a character somewhere which matches this, and be satisified. (For example, a space trivially matches this -- it's a character, and it's not in the range A through Z.)
If you use a regex dialect which understands word boundaries with \b, try
/\b[a-z][A-Za-z]*/
to match a token which has a word boundary on its left, and a lowercase character adjacent to it. (I am ignoring your locale extension, which is not portable and possibly not well-defined.)
In isolation, the /g flag doesn't do anything. If you have a language which supports it, and use a regex in a while loop or similar, it will cause the engine to return all the matches in the string, one at a time, inside the loop; but without further context, we have no idea whether that is actually true here.
To match all capital letters from your initial range, you may use [A-ZÀ-ÖØ-Þ] character class. To match all lowercase letters, [a-zß-öø-ÿ]. Note that × and ÷ are not letters, I removed them from these classes.
To make sure the whole string consists of these letters only, and the first char is not an uppercase letter, use
/^[a-zß-öø-ÿ][A-Za-zÀ-ÖØ-öø-ÿ]*$/
See the regex demo.
JS demo:
var strs = ['foo','fòo','Foo',' ','.',','];
var rx = /^[a-zß-öø-ÿ][A-Za-zÀ-ÖØ-öø-ÿ]*$/;
for (var s of strs) {
console.log(s,"=>",rx.test(s));
}
To extract words, use custom boundaries:
var s = 'foo,fòo,Foo';
var rx = /(?:[^A-Za-zÀ-ÖØ-öø-ÿ]|^)([a-zß-öø-ÿ][A-Za-zÀ-ÖØ-öø-ÿ]*)(?![A-Za-zÀ-ÖØ-öø-ÿ])/g;
var m, res=[];
while(m=rx.exec(s)) {
res.push(m[1]);
}
console.log(res);
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 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