JavaScript regex with below rules - javascript

Need to create a regex for a string with below criteria
Allowable characters:
uppercase A to Z A-Z
lowercase a to z a-z
hyphen `
apostrophe '
single quote '
space
full stop .
numerals 0 to 9 0-9
Validations:
Must start with an alphabetic character a-zA-Z or apostrophe
Cannot have consecutive non-alpha characters except for a full stop followed by a space.
The regex I have from the previous question in this forum. Business came back and want to allow string starting with apostrophe along with [a-zA-Z]. This break some previous validations.
eg: a1rte is valid
'tyer4 is valid
'4rt is invalid
^(?!.*[0-9'`\.\s-]{2})[a-zA-Z][a-zA-Z0-9-`'.\s]+$
Please advise.

You might use
^(?=[a-zA-Z0-9`'. -]+$)(?!.*[0-9'` -]{2})[a-zA-Z'][^\r\n.]*(?:\.[ a-z][^\r\n.]*)*$
Explanation
^ Start of string
(?=[a-zA-Z0-9`'. -]+$) Assert only allowed characters
(?!.*[0-9'` -]{2}) Assert not 2 consecutive listed characters
[a-zA-Z'] Match either a char a-zA-Z or apostrophe
[^\r\n.]* Optionally match any char except a newline or a dot
(?:\.[ a-z][^\r\n.]*)* Optionally repeat matching a dot only followed by a space or char a-z
$ End of string
Regex demo

Related

Regular expression to validate a string starts with a char and contains allowed chars

I need help with my regular expression written in javascript.
I have tried using the regularExpression generator online, and the best i can come up with is the this:
^[a-z.-]{0,50}$
The expression must validate the following
String first char MUST start with a-z (no alpha)
String can contain any char in range a-z (no alpha), 0-9 and the characters dash "-" and dot "."
String can be of max length 50 chars
Examples of success strings
username1
username.lastname
username-anotherstring1
this.is.also.ok
No good strings
1badusername
.verbad
-bad
also very bad has spaces
// Thanks
Almost (assuming "no alpha" means no uppercase letters)
https://regex101.com/r/O9hvLP/3
^[a-z]{1}[a-z0-9\.-]{0,49}$
The {1} is optional, I put it there for descriptive reasons
I think this should cover what you want
^[a-z][a-z0-9.-]{0,49}$
That is starts a-z but then has 0-49 of a-z, 0-9 or .-
Live example: https://regexr.com/5k8eu
Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add A-Z as well!
If the . and - can not be at the end, and there can not be consecutive ones, another option could be:
^[a-z](?=[a-z0-9.-]{0,49}$)[a-z0-9]*(?:[.-][a-z0-9]+)*$
Explanation
^ Start of string
[a-z] Match a single char a-z
(?=[a-z0-9.-]{0,49}$) Assert 0-49 chars to the right to the end of string
[a-z0-9]* Match optional chars a-z0-9
(?:[.-][a-z0-9]+)* Optionally match either . or - and 1+ times a char a-z0-9
$ End of string
Regex demo

Regex to not allow special character without prefix or suffix

I was writing regex for the following validate a string. I wrote the following regex.
^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}$
it validates for
No space in beginning.
no two consecutive space allowed.
The problem is it allows a single special character. it should not allow a special character unless it is suffixed or prefixed with alpha-numeric character.
Examples:
# -> not allowed.
#A or A# or A2 or 3A is allowed.
One option is to assert that the string does not contain a single "special" char or 2 special chars next to each other using a negative lookahead.
^(?!.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s])(?!.*(?:^| )[^a-zA-Z0-9\s](?!\S))\S+(?: \S+)*$
Explanation
^ Start of string
(?! Negative lookahead, assert that what is at the right does not contain
.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s] match 2 chars other than a-zA-Z0-9 or a whitespace char next to each other
) Close lookahead
(?! Negative lookahead, assert that what is at the right does not contain
.*(?:^| )[^a-zA-Z0-9\s](?!\S) Match a single char other than a-zA-Z0-9 or a whitespace char
) Close lookahead
\S+(?: \S+)* Match 1+ non whitespace chars and optionally repeat a space and 1+ non whitespace chars
$ End of string
Regex demo
Please omit the '$' symbol from the regex because it represents the end of the sentence.
^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}
So when applying the above regex to the following, it finds only '# '.
#A A# A2 3A

Regex for validating statement descriptor for credit card statements

I'm trying to validate a string entered by the user to be used as the statement description on the credit card statement to describe the purchase.
The requirements are:
Must be between 5 and 22 characters long
Must contain at least one letter (case doesn't matter)
Cannot contain these characters: < > \ ' "
Only ASCII characters allowed
Here's what I've got so far, which is kind of working:
/^(?=.*?[a-zA-Z])[a-zA-Z0-9]{5,22}$/gm
...in that it correctly checks the length for 5-22 characters long and checks for at least one letter. However, it disallows all special characters and diacritics instead of just the few that aren't allowed. How do I modify it to allow the other allowed characters?
You could use a positive lookahead to assert a character and a negative lookahead to assert not to match any character listed in the character class.
For Javascript you can use the case insensitive flag /i and use [a-z].
Edit: As Wiktor Stribiżew points out, to match only ASCII characters you could use [\x00-\x7F] instead of using a dot.
^(?=.*[a-z])(?!.*[<>\\'"])[\x00-\x7F]{5,22}$
^ Start of string
(?=.*[a-z]) Positive lookahead to check if there is a ASCII letter
(?!.*[<>\\'"]) Negative lookahead to check that there is not any of the chars in the character class
[\x00-\x7F]{5,22} Match any ASCII character 5 - 22 times
$ End of the string
For example:
const regex = /^(?=.*[a-z])(?!.*[<>\\'"])[\x00-\x7F]{5,22}$/gmi;
See the regex demo
You may use
/^(?=[^a-z]*[a-z])(?:(?![<>\\'"])[\x00-\x7F]){5,22}$/i
/^(?=[^a-z]*[a-z])(?![^<>\\'"]*[<>\\'"])[\x00-\x7F]{5,22}$/i
If you mean printable ASCII chars are allowed use
/^(?=[^a-z]*[a-z])(?:(?![<>\\'"])[ -~]){5,22}$/i
/^(?=[^a-z]*[a-z])(?![^<>\\'"]*[<>\\'"])[ -~]{5,22}$/i
Details
^ - start of string
(?=[^a-z]*[a-z]) - there must be at least 1 ASCII letter in the string
(?:(?![<>\\'"])[ -~]){5,22} - five to twenty-two occurrences of any printable ASCII char other than <, >, \, ' and " (if [\x00-\x7F] is used, any ASCII char other than the chars in the negated character class)
(?![^<>\\'"]*[<>\\'"]) - no <, >, \, ' and " allowed in the string
$ - end of string.

validation format of javascript

I found these javascript validation codes:
<script type="text/javascript">
function validasi_input(form){
pola_username=/^[a-zA-Z0-9\_\-]{6,100}$/;
if (!pola_username.test(form.username.value)){
alert ('Username minimal 6 karakter dan hanya boleh Huruf atau Angka!');
form.username.focus();
return false;
}
return (true);
}
</script>
I want to ask about this part:
pola_username=/^[a-zA-Z0-9\_\-]{6,100}$/;
does anyone can tell me how to understand this kind of format? is it format for letter, or number, or characters?
/^[a-zA-Z0-9\_\-]{6,100}$/;
In english this means: that a string can have any letter either uppercase or lowercase, numbers, underscores, and hyphens. A minimum length of 6 characters, and a maximum length of 100.
Further details:
The string must start with either a letter, number, underscore, or hyphen.
/^[a-zA-Z0-9\_\-]{6,100}$/
^ asserts that we are at the beginning of the string
[a-zA-Z0-9_-] string can have any letter either uppercase , lowercase, numbers, underscores, or hyphens.
{6,100} matches a length of character having from 6 to 100
$ asserts that we are at the end of the string
Various RegEx explanation/testing tools.
1. Explain RegEx
2. RegEx101
3. Debuggex Demo
^[a-zA-Z0-9\_\-]{6,100}$
^ is an anchor. It asserts position at start of the string
[a-zA-Z0-9\_\-]{6,100} match a single character present in the list below
{6, 100}: Between 6 and 100 times, as many times as possible, giving back as needed
a-z a single character in the range between a and z (case sensitive)
A-Z a single character in the range between A and Z (case sensitive)
0-9 a single character in the range between 0 and 9
\_ matches the character _ literally
\- matches the character - literally
$ is an anchor. It asserts position at end of the string.
An alternative regex using flags would be:
/^[a-z\d\_\-]{6,100}$/i
Here \d matches digits (0-9), and flag i denotes case insensitivity.
This is what regular expressions do to perform matches, for starters:
(source: gyazo.com)

regular expression to avoid only special chars

I'm validating a input text box. I'm new to regexp. I want an expression which throws a validation error if all the characters of input are special characters. but it should allow special characters in the string.
-(**&^&)_) ----> invalid.
abcd-as jasd12 ----> valid.
currently validating for numbers and alphabets with /^[a-zA-Z0-9-]+[a-z A-Z 0-9 -]*$/
/[A-Za-z0-9]/ will match positive if the string contains at least 1 letter or number, which should be the same as what you're asking. If there are NO letters or numbers, that regex will evaluate as false.
According to your comment, special characters are !##$%^&*()_-, so you could use:
var regex = /^[!##$%^&*()_-]+$/;
if (regex.test(string))
// all char are special
If you have more special char, add them in the character class.
Use negative Lookahead:
if (/^(?![\s\S]*[^\w -]+)[\s\S]*?$/im.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
DEMO
EXPLANATION:
^(?!.[^\w -]+).?$
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*[^\w -]+)»
Match any single character «.*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match a single character NOT present in the list below «[^\w -]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A word character (letters, digits, and underscores) «\w»
The character “ ” « »
The character “-” «-»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
~[^a-zA-z0-9 ]+~ it will matches if the String doesnot contains atleast one alphabets and numbers and spaces in it.
Demo

Categories

Resources