Excluding $ in a regex in CF - javascript

I am working through some different form validation types and I am having trouble getting all the items on my wishlist to work.
My code for my cfinput is this (works the same as a regular form input and has some canned javascript validation)
<cfinput type="Text" name="negdays"
range="0,23"
pattern="^(([^0]{1})([0-9])*|(0{1}))?$"
message="Negative Days must be a number between 0 and 23"
required="No" width="2" >
This one should, and does, exclude everything I need except the $. I am having difficulty stopping the form from accepting the $.
Another example that is similar is this one where I want a range and to keep it numeric, so I mixed the validation types
<cfinput type="text" name="achamount"
validate = "range,numeric"
range = "0,99999"
message="ACH Amount must be a range from 0 - 99999 and numeric only" >
... and it works perfect - except for one problem: a $ is allowed.
So I thought maybe I could add to it with a regex like this:
<cfinput type="text" name="achamount"
validate = "range,numeric,regex"
range = "0,99999"
pattern="^\d"
message="ACH Amount must be a range from 0 - 99999 and numeric only" >
But my pattern is of course only to limiting it to numeric, which I am already doing. I need my pattern to exclude the dollar signs. But as a special character its not behaving like the other stuff I want to get rid of.
Any ideas or suggestions? Everything I have tried either does not work or breaks all the other validation on the page.

Solution: Matching Only Numbers
You don't need to specifically exclude $ - to only allow numeric digits, you simply need to ensure every character matches \d.
To do this, you need to anchor the start and end of the regex to the start and the end of the input, which is done with the regex metacharacters ^ and $ respectively. (If you ever need to use either of these characters as literals, prefix them with a backslash.)
So for an integer between 0 and 99999 you want:
^\d{1,5}$
Matching an integer between 0 and 23 works the same way thing, but the central part of the pattern needs to be complex, to ensure you don't get 24 or above:
^(?:[03-9]|1\d?|2[0-3]?)$
The three alternatives here are:
* [03-9] matches any single digit except 1 or 2.
* 1\d? matches 1, or 1 followed by any digit.
* 2[0-3]? matches 2, or 2 followed by any digit upto 3.
The (?:..) is to ensure the ^ and $ still apply to the entire string.
(Of course, you could also just use ^\d{1,2}$ then later check if it's less than 24.)
Bonus Info: Excluding Characters
As above, you don't need to do this in this case, but if you encounter a situation where you did need to exclude $, you could do it either using a negative character class:
^[^$]{1,5}$
Or using a negative lookahead:
^(?:(?!\$).){1,5}$
This latter one is a bit more complicated, but it allows more flexibility so is useful to be aware of.
A lookahead is another form of anchor (it matches at a position, but doesn't consume the characters it matches). When used against a item that has a quantifier (the {1,5} bit) attached, you need to group both items together for it to apply correctly. (i.e. If you only did (?!\$).{1,5} the negative lookahead would only be checked for the first character, not all five.)
Note that outside of a character class $ must be escaped as \$ to prevent it's special meaning of "end of string anchor". Inside a character class it is just a regular character.
(Hopefully this explanation is clear - let me know if further information or clarification would be useful.)

Your regex ^(([^0]{1})([0-9])*|(0{1}))?$ can be simplified quite a bit. It seems that you want either a single digit preceeded by a 0 or maximum 2 digits.
Try this: ^\d{2}$

What about adding the $ to a range of characters you don't allow?
pattern="[^$]"

Related

Regex - Only detect if all single digits in all four octets [duplicate]

Overview:
I am trying to combine two REGEX queries into one:
\d+\.\d+\.\d+\.\d+
^(?!(10\.|169\.)).*$
I wrote this as a two part query. The first part would isolate IPs in a block of text and after I copy and paste this I select everything and that does not being with a 10 or 169.
Questions:
It seems like I am over complicating this:
Can anybody see a better way to do this?
Is there a way to combine these two queries?
Sure. Just put the anchored negative look ahead at the start:
^(?!10\.|169\.)\d+\.\d+\.\d+\.\d+$
Note: Unnecessary brackets have been removed.
To match within a line, ie remove the anchors and use a "word boundary" \b as the anchor:
\b(?!10\.|169\.)\d+\.\d+\.\d+\.\d+
A quick-and-gimme-regex style answer
Basic one (whole string looks like an IP): ^\d+\.\d+\.\d+\.\d+$
Lite (period-separated 4-digit chunks, a whole word): \b\d+\.\d+\.\d+\.\d+\b
Medium (excluding junk like 1.2.4.6.7.9.0): (?<!\d\.)\b\d+\.\d+\.\d+\.\d+\b(?!\.\d+)
Advanced 1 (not starting with 10 or 169): (?<!\d\.)\b(?!(?:1(?:0|69))\.)\d+\.\d+\.\d+\.\d+\b(?!\.\d+)
Advanced 2 (not ending with 8 or 10): (?<!\d\.)\b\d+\.\d+\.\d+\.(?!(?:8|10)\b)\d+\b(?!\.\d+)
Details for the curious
The \b is a word boundary that makes it possible to match exact "words" (entities consisting of [a-zA-Z0-9_] characteters) inside a longer text. So, if we do not want to match 12.12.23.56 inside g12.12.23.56g, we use the Lite version.
The lookarounds together with the word boundary, make it possible to further restrict the matches. (?<!\d\.) - a negative lookbehind - and a (?!\.\d+) - a negative lookahead - will fail a match if the IP-resembling substring is preceded with a digit+. or followed with a .+digit. So, we do not match 12.12.34.56.78.90899-like entities with this regex. Choose Medium regex for that case.
Now, you need to restrict the matches to those that do not start with some numeric value. You need to make use of either a lookbehind, or a lookahead. When choosing between a lookbehind or a lookahead solution, prefer the lookahead, because 1) it is less resource consuming, and 2) more flavors support it. Thus, to fail all matches where IP first number is equal to 10 or 169, we can use a negative lookahead anchored after the leading word boundary: (?!(?:1(?:0|69))\.). The syntax is (?!...) and inside, we match either 1 followed with 0 and then a ., or 1 followed with 69 and then .. Note that we could write (?!10\.|169\.) but there is some redundant backtracking overhead then, as 1 part is repeating. Best practice is to "contract" alternations so that the beginning of each branch did not repeat, make the alternation group more linear. So, use Advanced 1 regex version to get those IPs.
A similar case is the Advanced 2 regex for getting some IPs that do not end with some value.

Password validation regex: require and forbid certain characters

I have an MVC form with jQuery validation and System.ComponentModel.DataAnnotations
Problem is if I enter & in the password textbox then jQuery and MVC Model.Isvalid allows it, even though it's not one of the allowed characters.
I have tried to search for this on Google but the results I get back have nothing to do with the issue. i.e. JavaScript: client-side vs. server-side validation - Stack Overflow
My regex is below in case I have made a mistake with that.
RegularExpression("^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,10})",
ErrorMessage = "{0} must be between 6 and 10 characters and have at least 1 upper case letter, 1 lower case letter, 1 number and contain either ##$%")
The pattern in your example ^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,10}) uses positive lookaheads to ensure certain character classes are present in the input string but it will not in any way prevent other types of characters to appear. Each lookahead group starts with .* which allows literally anything hence & or any other character as a matter of fact will be accepted in the input string and whatever a lookahead signifies will be enforced in addition.
In other words, this approach using only positive lookaheads will make some types of characters required but it will not make any characters disallowed.
To overcome this, you can simply add another lookahead group but this time a negative one:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%])(?!.*[&]).{6,10}$
Also, pay attention to end the pattern with string terminator $ (which was missing in your example). Without that the regex engine will produce a match for inputs that are more than 10 characters long.
See example here.

Why are my optional characters not being caught?

I'm trying to create a regex to test passwords against. My current one checks for the following:
One Uppercase Letter
One Lowercase Letter
One number
Currently, the user can't enter special characters, however I'm trying to add that as an optional check (so Testing1 and Testing1! should both match). I've tried:
^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])(A-Za-z\d[$#$!%*#?&]?){8,}$
But it doesn't catch it. I have a feeling my special character set is in the wrong place, but I'm not sure where to place it.
Where do I add my list of special characters as optional checks?
There's many ways that you can set up your regex, such as creating a whitelist, or a blacklist, for types of characters. This one in particular creates a whitelist for characters that can be used which seems to be what you are looking for.
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9$#$!%*#?&]{8,}$
Regex Breakdown:
^ // Assert position at start of the line
(?=.*[A-Z]) // First positive lookahead, makes sure a capital character exists
(?=.*[a-z]) // Make sure a lowercase character exists
(?=.*[0-9]) // Make sure a number exists
[A-Za-z0-9$#$!%*#?&] // All of the possible characters that can be typed
{8,} // 8 to infinity characters
$ // Assert position at end of line
Since you say that you want special characters as optional, they are just placed in the possible characters that can be typed, but they are not validated by any positive lookaheads.
See this regex in action on regex101. Keep in mind, the modifiers gm are there to validate across lines in this example and should probably be removed in your use case.
Of course you may have reasons for the "whitelist" approach, but a more common approach, and one you may want to look into trying sometime, is to allow almost anything (blacklist), and then validate that a certain criteria is met.

Match Multiple validation on 1 input with javascript

I'd like to find a way to match the length of an input as well as the characters inside that input using javascript. Normally I'd just use the jquery plugin for validation, but for the client we can't use any 3rd party modules.
The input requires a string of characters between 6-13 but also does not allow the < or > characters within the values.
I'd like a way to check both the length of the string to make sure its between 6-13 but also reject the string if it contains < or >. I'm assuming this can be done with Regex, but my skills are severely lacking. The user should be able to see a message based on length and incorrect characters depending on what they are typing. Any quick methods out there?
or use this pattern
^(?!.*[<>]).{6,13}$
Demo
^ beginning of line
(?! Negative Look-Ahead
. Any character except line break
* (zero or more)(greedy)
[<>] Character Class [<>]
) End of Negative Look-Ahead
. Any character except line break
{6,13}$ (repeated {6,13} times) to the end

regex for specific phone number arrangement

i'm currently using this regex
"/^([0-9\(\)\/\+ \-]*)$/",
which is fine,but the problem is i am also using a masking script,
which produces this line automatically,
(___) ___-____
and it messes up my validation, what regex code can allow me to verify only this type of input from the use
(999) 999-9999
and also not accept a "blank" input field from user when entered. any length is fine, as long as it only accepts this inputs that i mentioned above.
This should work:
^\(\d{3}\)\s{0,1}\d{3}-\d{3}$
Breaking this regexp:
\(\d{3}\) matches only three numbers between brackets.
\s{0,1} matches only 0 or 1 space.
\d{3}-\d{3} matches only three numbers followed by '-' and then three other numbers.
First, when asking about regular expressions, you should always say which language or tool you are using because that affects what features are available and which characters need to be quoted with backslash. I'll assume you're asking about JavaScript based on your question's tags.
You say any length is fine. I shall take that to mean that each sequence of consecutive digits can contain any number of digits from one to infinity. I shall assume there's exactly one space and exactly one dash. On that basis, your RE is:
/^\(\d+\) \d+-\d+$/
If, as is more likely, you want to limit the lengths of the digit sequences, you would say something like:
/^\(\d{3,4}\) \d{3}-\d{1,10}$/
(three or four digits, exactly three digits, one to ten digits).
I have omitted any capturing parentheses (...) , which are a bit redundant if you're capturing the whole string ^(....)$ .
Here's a concise summary of JavaScript regex syntax:
http://www.regextester.com/jssyntax.html
Formatting and validation are two very different things. If you try to mix them, you will fail.
That being said, before performing validation you should strip all formatting characters from your string, then validate the content.
// remove everything that isn't a digit
var strippedNumber = value.replace(/\D/g, '');
if (strippedNumber.length === 10) {
// valid phone number
}

Categories

Resources