Regular expression allow numbers and digits validation pattern - javascript

I am trying to check if a form input is valid based on a regex pattern using javascript.
The form input should look like this: xxxx-xxx-xxxx allowing for both numbers and letters
Right now it only works with digits as I have it setup which is now being changed to allow letters as well. is there a way to change the regex I have to allow numbers and letters and still format as is?
4 letters or numbers A DASH 3 letters or numbers A DASH 4 letters or numbers
validation rule
medNumber: [
{
required: true,
pattern: /^\d{4}?[- ]?\d{3}[- ]?\d{4}$/,
message: "Please enter your #.",
trigger: ["submit", "change", "blur"]
}
],

[A-Za-z0-9] will match only alphanumeric characters.
/^[A-Za-z0-9]{4}?[-]?[A-Za-z0-9]{3}[-]?[A-Za-z0-9]{4}$/
I've also removed the spaces from within your instances of [- ] because that will allow matches such as
xxxx xxx xxxx
In your spec you mention a dash is required, not a space.

The rule \d allows only for digits. So you need to change every occurrence of this to \w, which allows any alphanumeric character (letters and digits). So you'd get the following:
/^\w{4}?[- ]?\w{3}[- ]?\w{4}$/
For future reference, I'd suggest looking at regexone.com. It has helped me a ton with learning all the regex rules. You can also use regex101.com for easy testing of regex patterns.
Edit:
I was probably a bit too quick on this one. As #David mentioned in the comment, \w also includes underscores. If you don't want that, you should look at his answer instead :)

Related

Regex for a valid hashtag

I need regular expression for validating a hashtag. Each hashtag should starts with hashtag("#").
Valid inputs:
1. #hashtag_abc
2. #simpleHashtag
3. #hashtag123
Invalid inputs:
1. #hashtag#
2. #hashtag#hashtag
I have been trying with this regex /#[a-zA-z0-9]/ but it is accepting invalid inputs also.
Any suggestions for how to do it?
The current accepted answer fails in a few places:
It accepts hashtags that have no letters in them (i.e. "#11111", "#___" both pass).
It will exclude hashtags that are separated by spaces ("hey there #friend" fails to match "#friend").
It doesn't allow you to place a min/max length on the hashtag.
It doesn't offer a lot of flexibility if you decide to add other symbols/characters to your valid input list.
Try the following regex:
/(^|\B)#(?![0-9_]+\b)([a-zA-Z0-9_]{1,30})(\b|\r)/g
It'll close up the above edge cases, and furthermore:
You can change {1,30} to your desired min/max
You can add other symbols to the [0-9_] and [a-zA-Z0-9_] blocks if you wish to later
Here's a link to the demo.
To answer the current question...
There are 2 issues:
[A-z] allows more than just letter chars ([, , ], ^, _, ` )
There is no quantifier after the character class and it only matches 1 char
Since you are validating the whole string, you also need anchors (^ and $)to ensure a full string match:
/^#\w+$/
See the regex demo.
If you want to extract specific valid hashtags from longer texts...
This is a bonus section as a lot of people seek to extract (not validate) hashtags, so here are a couple of solutions for you. Just mind that \w in JavaScript (and a lot of other regex libraries) equal to [a-zA-Z0-9_]:
#\w{1,30}\b - a # char followed with one to thirty word chars followed with a word boundary
\B#\w{1,30}\b - a # char that is either at the start of string or right after a non-word char, then one to thirty word (i.e. letter, digit, or underscore) chars followed with one to thirty word chars followed with a word boundary
\B#(?![\d_]+\b)(\w{1,30})\b - # that is either at the start of string or right after a non-word char, then one to thirty word (i.e. letter, digit, or underscore) chars (that cannot be just digits/underscores) followed with a word boundary
And last but not least, here is a Twitter hashtag regex from https://github.com/twitter/twitter-text/tree/master/js... Sorry, too long to paste in the SO post, here it is: https://gist.github.com/stribizhev/715ee1ee2dc1439ffd464d81d22f80d1.
You could try the this : /#[a-zA-Z0-9_]+/
This will only include letters, numbers & underscores.
A regex code that matches any hashtag.
In this approach any character is accepted in hashtags except main signs !##$%^&*()
(?<=(\s|^))#[^\s\!\#\#\$\%\^\&\*\(\)]+(?=(\s|$))
Usage Notes
Turn on "g" and "m" flags when using!
It is tested for Java and JavaScript languages via https://regex101.com and VSCode tools.
It is available on this repo.
Unicode general categories can help with that task:
/^#[\p{L}\p{Nd}_]+$/gu
I use \p{L} and \p{Nd} unicode categories to match any letter or decimal digit number. You can add any necessary category for your regex. The complete list of categories can be found here: https://unicode.org/reports/tr18/#General_Category_Property
Regex live demo:
https://regexr.com/5tvmo
useful and tested regex for detecting hashtags in the text
/(^|\s)(#[a-zA-Z\d_]+)/ig
examples of valid matching hashtag:
#abc
#ab_c
#ABC
#aBC
/\B(?:#|#)((?![\p{N}_]+(?:$|\b|\s))(?:[\p{L}\p{M}\p{N}_]{1,60}))/ug
allow any language characters or characters with numbers or _.
numbers alone or numbers with _ are not allowed.
It's unicode regex, so if you are using Python, you may need to install regex.
to test it https://regex101.com/r/NLHUQh/1

Regex allowing 3 numbers with no special characters and space

I am using a regex as /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?$/ which allow only 3 numbers and no special characters
I need to include space check as well.
Please help me
I don't know why your regular expression is so complex. If you need three digits with no other characters, just use this:
/^[0-9]{3}$/
That will only validate strings that are three digits with nothing else, "324", "857", "111". You get it.
If you have other requirements, please update your question with them.

regex for alphaspecialnumeric

I would like to check few of my text boxes that must satisfy the following conditions:
Alphabets i meant are from a-z(uppercase and lower case) numbers 0-9 and special characters are ~`!##$%^&*()-_+={}[];:'",.<>/?
It can contain only alphabets
It cannot contain only numbers
It cannot contain only special characters
It cannot contain only numbers and special characters
It can contain alphabets,numbers and special characters
It can contain alphabets and numbers
It can contain alphabets and special charcters
I found a solution but seems not working for me:
/^[a-z0-9/. -!##$%^&*(){}:;"',/?]+$/i
I am checking it as:
var alpha=/^[a-z0-9/. -!##$%^&*(){}:;"',/?]+$/i;
if (!alpha.test(username.value))
{
alert('Invalid username');
document.theForm.username.focus();
return false;
}
The problem can be restated as that of matching a string containing ONLY the characters
A-Za-z0-9~`!##$%^&*()-_+={}[];:'",.<>/?
such that at least one of them is a letter.
Fortunately, you've covered all the printable characters in the range U+0021 to U+007F, so that the desired regex is simply
[!-~]*[A-Za-z][!-~]*
EDIT: On closer reading, I noticed you did not allow the backslash! If you want to allow the backslash, the regex above is okay; if not, you should modify it like so:
[!-\[\]-~]*[A-Za-z][!-\[\]-~]*
It's a bit uglier, because to exclude the backslash we have to say
All characters in the range ! to [ union characters in the range ] to ~, and the explicit mention of [ and ] requires escaping with, you guessed it, the \.
Hopefully you meant to allow the \ so you can use the simpler regex above.
EDIT 2
To make the regex more efficient, you should use a reluctant quantifier (as kcsoft did):
[!-~]*?[A-Za-z][!-~]*
Also for JavaScript, but not for Java if you are using matches, you should anchor the regex to match the whole string, giving this in JavaScript:
/^[!-~]*?[A-Za-z][!-~]*$/
And, as you did in your question, you can shorten it a bit more by using the i modifier:
/^[!-~]*?[A-Z][!-~]*$/i
Can you give some input examples. Can you try this?
/.*?[a-zA-Z]+.*/
Or if you need to specify the list of special characters:
/[list of chars]*?[a-zA-Z]+[list of chars]*/

RegEx a name with special characters in javascript

I'm relative new to RegEx and I've encountered a problem. I want to regex a name. I want it to be max 100 characters, contain at least 2 alphabetic characters and it will allow the character '-'.
I have no problem to only check for alphabetic characters or both alphabetic characters and hyphen but I dont't want a name that potantially can be '---------'.
My code without check for hyphens is
var nameRegExp = /^([a-z]){2,100}$/;
An explanation for the code is appreciated as well.
Thanks!
I guess
/^(?=.*[a-z].*[a-z])[a-z-]{1,100}$/
the lookahead part (^(?=.*[a-z].*[a-z])) checks if there are at least two letters. This pattern ("start of string, followed by...") is a common way to express additional conditions in regexes.
You can limit the number of - by adding a negative assertion, as #Mike pointed out:
/^(?=.*[a-z].*[a-z])(?!(?:.*-){11,})[a-z-]{1,100}$/ // max 10 dashes
however it might be easier to write an expression that would match "good" strings instead of trying to forbid "bad" ones. For example, this
/^[a-z]+(-[a-z]+)*$/
looks like a good approximation for a "name". It allows foo and foo-bar-baz, but not the stuff like ---- or foo----bar----.
To limit the number of - you could add a negative look-ahead, where the number 3 is one more than the maximum number you want to allow
/^(?!(?:[a-z]*-){3,})(?=-*[a-z]-*[a-z])[a-z-]{2,100}$/

Javascript Regex Pattern

I'm trying to create a regex pattern that allows the user to create a username with the following specifications. (For the purposes of this initial pattern, I'm only using standard american English alphabet.
The first character must be an alphabetic letter (uppercase or lowercase). [a-zA-Z]
The last character must be a alphanumeric (uppercase or lowercase). [a-zA-Z0-9]
Any characters in between must be letters or numbers with one rule:
The user can use a period(.), dash(-), or underscore(_) but it must be followed by an alphanumeric character. So no repeats of one or more of these characters at a time.
I've tried the following regex pattern but am not getting the results I was hoping for. Thanks for taking the time to help me on this.
^[a-zA-Z]([a-zA-Z0-9]+[._-]?[a-zA-Z0-9]+)+$
EDIT
It might actually be working the way I expected. But I'm always getting two matches returned to me. The first one being the entire valid string, the second being a shortened version of the first string usually chopping off the first couple of characters.
Examples of valid inputs:
Spidy
Spidy.Man
Ama-za-zing_Spidy
Examples of invalid inputs:
Extreme___Spidy (repeated underscores)
The_-_Spidy (repeated special characters)
_ _ SPIDY _ _ (starts and ends with special characters)
Sounds like this pattern:
^[a-zA-Z]([._-]?[a-zA-Z0-9])*$
^[a-zA-Z]([._-]?[a-zA-Z0-9]+)*$

Categories

Resources