Knockout Js Regex no negative numbers - regex

I'm trying to find a regex code to disable negative numbers for the user input.
I'm playing around with the code abit trying to find the right one but haven't had much success.
my current code is:
Price: ko.observable().extend({
required: true,
pattern: '^[0-9].$'
})

In such case, Why do you need to allow user to enter minus numbers in your input field and validate the input against negative number?
Instead you can prevent the User from entering negative numbers/strings.
This uses JavaScript, but you don't have to write your own validation routine. Instead just check the validity.valid property. This will be true if and only if the input falls within the range.
Solution 1:
<html>
<body>
<form action="#">
<input type="number" name="test" min=0 oninput="validity.valid||(value='');">
</form>
</body>
</html>
Solution 2:
The below solution supports to validate multiple inputs.
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function(){
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
<input type="number" min="0" />
Solution 3:
I haven't tested the below solution, But this might help as well...
Either '/^\d+$/' OR '^\d+$' pattern may help you along with your current approach.
Price: ko.observable().extend({
required: true,
pattern: '/^\d+$/'
})
Original Solution and Reference here..
Hope this helps...

You could use the digit group \d
pattern: '^\d+\.?$'
This matches the following:
The number must start at the beginning of the line
Must consist of 1 or more digits
Can have the character "." 0 or 1 times
The number must end at the end of the line
Here are some examples of matches: "34", "5", "45687654", "1.", "198289."
I notice that you said you wanted to avoid negative numbers, your solution was to squish the number to the beginning and end of the line. You can also use a negative lookbehind to check that the number does not have a negative sign, such as with
pattern: '(?<!-)\b\d+\.?'
I also added a word boundary check (\b) so that is would not try to match the 23 in -123

Related

regex fail on razor

I have a simple regex - [a-zA-Z0-9][^\s] - that checks that there are at least two characters and the second one is not white space. This works fine in C# but not in an <input> field in Razor.
Here is the field in Razor:
<input type="search" name="search" required pattern="[a-zA-Z0-9][^\s]">
Here is a test in C#:
Console.WriteLine("string 'c-III' is valid = {0}", rgx.IsMatch("c-III"));
Console.WriteLine("string 'c ' is valid = {0}", rgx.IsMatch("c "));
Here is the result:
string 'c-III' is valid = True
string 'c ' is valid = False
This works as expected as well in regex101.com
When I type c-III I get the error message: Please match the requested format.
The expression needs to validate the following:
minimum of 2 characters
second character cannot be white space
I am not sure if the expression need to be adjusted or if the problem is somewhere else. Any help will be appreciated

HTML5 Pattern Validation

I'm trying to make a password field with the following requirements.
Minimum of 8 characters
Max of 16 characters
Must contain one number OR special characters
Only the following special characters may be used:
, ` ~ ! # # $ % ^ & * ) ; ' [ ] "{ } .
I read this Stack Overflow question and tried to follow what was going on in the example. This is what I came up with:
^[a-zA-Z](?=.*[0-9.,`~!##$%^&*\);'\[\]\"\{\}.]).{8,16}+
This is how I'm using the pattern:
<input id="Password" class="form-control" pattern="^[a-zA-Z](?=.*[0-9.,`~!##$%^&*\);'\[\]\"\{\}.]).{8,16}+" required="required" type="password">
This regex expression, however, does not seem to be working as intended. If I enter "password" as my input it should be rejected. Instead, this string is being accepted. I would greatly appreciate it if someone can give me a hand with this.
Here is how you can use the pattern attribute:
input:valid {
color: green;
}
input:invalid {
color: red;
}
<form name="form1">
<input pattern="(?=.*[\d,`~!##$%^&*);'[\]\x22{}.]).{8,16}" title="Please check the input!"/>
<input type="Submit"/>
</form>
You only need to "escape" the double quote as \x22 and the ] symbol inside the character class.
No anchors are required since the pattern is anchored by default.
The following code would check your password according to your rules (though in 2 regexes)
var psw = 'yourPas$word';
if (
// ensure the length is between 8 & 16
/^.{8,16}$/.test(psw) &&
// ensure the presence of a special char
/^.*[,`~!##$%^&*);'\[\]"{}.].*$/.test(psw)
) {
console.log('hurray is valid');
} else {
console.log('booo');
}
Use this regex in pattern to make sure the password contains both letters and numbers/symbols:
^(?=.*[a-z])(?=.*[\d,`~!##$%^&*);'[\]\x22{}]).{8,16}$
Further improvements possible.

Regex for IBAN allowing for white spaces AND checking for exact length

I need to check an input field for a German IBAN. The user should be allowed to leave in white spaces and input should be validated to have a starting DE and then exact 20 characters numbers and letters.
Without the white space allowance, I tried
^[DE]{2}([0-9a-zA-Z]{20})$
but I cannot find where and how I can add "white spaces anywhere allowed.
This should be simple, but I simply cannot find a solution.
Thanks for help!
Because you should use the right tool for the right task: you should not rely on regexps to validate IBAN numbers, but instead use the IBAN checksum algorithm to check the whole code is actually correct, making any regexp superfluous and redundant. i.e.: remove all spaces, rearrange the code, convert to integers, and compute remainder, here it's best explained.
Though, there am I trying to answer your question, for the fun of it:
what about:
^DE([0-9a-zA-Z]\s?){20}$
which only difference is allowing a whitespace (or not) after each occurence of a alphanumeric character.
here is the visualization:
edit: for the OP's information, the only difference is that this regexp, from #ulugbex-umirov: (?:\s*[0-9a-zA-Z]\s*) does a lookahead check to see if there's a space between the iso country code and the checksum (which only made of numerical digits), which I do not support on purpose.
And actually to support a correct IBAN syntax, which is formed of groups of 4 characters, as the wikipedia page says:
^DE\d{2}\s?([0-9a-zA-Z]{4}\s?){4}[0-9a-zA-Z]{2}$
example
If your UI is in Javascript, you can use that library for doing IBAN validation:
<script src="iban.js"></script>
<script>
// the API is now accessible from the window.IBAN global object
IBAN.isValid('hello world'); // false
IBAN.isValid('BE68539007547034'); // true
</script>
so you know this is a valid IBAN, and can validate it before the data is ever even sent to the backend. Simpler, lighter and more elegant… Why do something else?
Here is a list of IBANs from 70 Countries. I generated it with a python script i wrote based on this https://en.wikipedia.org/wiki/International_Bank_Account_Number
AL[a-zA-Z0-9]{2}\s?([0-9]{4}\s?){2}([a-zA-Z0-9]{4}\s?){4}\s?
AD[a-zA-Z0-9]{2}\s?([0-9]{4}\s?){2}([a-zA-Z0-9]{4}\s?){3}\s?
AT[a-zA-Z0-9]{2}\s?([0-9]{4}\s?){4}\s?
AZ[a-zA-Z0-9]{2}\s?([a-zA-Z0-9]{4}\s?){1}([0-9]{4}\s?){5}\s?
BH[a-zA-Z0-9]{2}\s?([a-zA-Z]{4}\s?){1}([a-zA-Z0-9]{4}\s?){3}([a-zA-Z0-9]{2})\s?
BY[a-zA-Z0-9]{2}\s?([a-zA-Z0-9]{4}\s?){1}([0-9]{4}\s?){5}\s?
BE[a-zA-Z0-9]{2}\s?([0-9]{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9]{2})\s?
VG[a-zA-Z0-9]{2}\s?([a-zA-Z0-9]{4}\s?){1}([0-9]{4}\s?){4}\s?
Original:
^[DE]{2}([0-9a-zA-Z]{20})$
Debuggex Demo
Modified:
^DE(?:\s*[0-9a-zA-Z]\s*){20}$
Debuggex Demo
This is the correct regex to match DE IBAN account numbers:
DE\d{2}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{2}|DE\d{20}
Pass: DE89 3704 0044 0532 0130 00|||DE89370400440532013000
Fail: DE89-3704-0044-0532-0130-00
Most simple solution I can think of:
^DE(\s*[[:alnum:]]){20}\s*$
In particular, your initial [DE]{2} is wrong, as it allows 'DD', 'EE', 'ED' as well as the intended 'DE'.
To allow any amount of spaces anywhere:
^ *D *E( *[A-Za-z0-9]){20} *$
As you want to allow lower letters, also DE might be lower?
^ *[Dd] *[Ee]( *[A-Za-z0-9]){20} *$
^ matches the start of the string
$ end anchor
in between each characters there are optional spaces *
[character class] defines a set/range of characters
To allow at most one space in between each characters, replace the quantifier * (any amount of) with ? (0 or 1). If supported, \s shorthand can be used to match [ \t\r\n\f] instead of space only.
Test on regex101.com, also see the SO regex FAQ
Using Google Apps Script, I pasted Laurent's code from github into a script and added the following code to test.
// Use the Apps Script IDE's "Run" menu to execute this code.
// Then look at the View > Logs menu to see execution results.
function myFunction() {
//https://github.com/arhs/iban.js/blob/master/README.md
// var IBAN = require('iban');
var t1 = IBAN.isValid('hello world'); // false
var t2 = IBAN.isValid('BE68539007547034'); // true
var t3 = IBAN.isValid('BE68 5390 0754 7034'); // true
Logger.log("Test 1 = %s", t1);
Logger.log("Test 2 = %s", t2);
Logger.log("Test 3 = %s", t3);
}
The only thing needed to run the example code was commenting out the require('iban') line:
// var IBAN = require('iban');
Finally, instead of using client handlers to attempt a RegEx validation of IBAN input, I use a a server handler to do the validation.

RNA second structure regexp pattern for HTML5

I need a RegExp to identify RNA Second structure in an HTML5 web page.
An RNA Second Structure is simply a string that contains ONLY dot points and balancing parentheses and it's used to identify the RNA shape and if we know the target RNA shape we could guess the sequence of bases that could make an RNA with that target shape.
Please note it should contains at least One dot ..
For example
.....((((...).))..)....
(((....)))
....(((..)))...()...(....((..)))
are true RNA Second Structures but
.....((((....)))...
....a.((((......))))......
((((()))))
are not true structures
These are all my failed attempts to identifying structures:
<input type="text" pattern="/[.()]/g" />
<input type="text" pattern="/[.()]/g" />
<input type="text" pattern="/[\.\(\)]/g" />
<input type="text" pattern="/[().]/g" />
<input type="text" pattern="/[()\.]/g" />
<input type="text" pattern="/[\.()]/g" />
I'm new to RegExp and I should publish my program in the web because my teacher ordered me to do so!
And PLEASE just tell me the RegExp I should use! My program ( libRNA ) itself checks the balancing of parentheses!
libRNA
It is impossible to do generalized bracket balancing (finitely many nesting levels of brackets) with the level of support of JavaScript RegExp. (In Perl, PCRE, .NET regular expression, it is possible to do generalized bracket balancing).
You can write a simple JavaScript function to check, though:
function isValidSequence(str) {
if (!/\./.test(str)) {
// Dot . not found
return false;
}
var openBrackets = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "(") {
openBrackets++;
} else if (str[i] === ")") {
if (openBrackets > 0) {
openBrackets--;
} else {
// Reject the case ..)(..
return false;
}
} else if (str[i] !== ".") {
// Garbage character, since it is not . or ( or )
return false;
}
}
// Check all brackets are properly closed
return openBrackets === 0;
}
/[().]+/g
would match everything that looks like an RNA Second Structure (i. e. a continuous sequence of dots and parentheses). You should first use this regex to find possible matches.
Then, you can check whether at least one dot is contained within each of those matches using
if (submatch.indexof(".") != -1)
But you can't check whether the parentheses are correctly balanced - for that you need a parser like nhahtdh suggested.
The problem here is that what you actually need to match is:
a = . | .(a) | (a). | .a | a.
The main problem why solving this with regular expressions will be hard if not impossible is that for every opening paranthesis there has to be a closing one.
It should be possible to do this with JavaScript. You need to do something like this:
Set paranthesis counter to 0. Iterate over the entire structure. When an opening paranthesis is found, increase counter. If you find a closing parenthesis, decrease the counter.
If at the end of the parsing the counter is back to zero, the structure is ok. Only thing missing now is the required dot. For that I would introduce another variable justOpened or something similar. When you find an opening paranthesis you set it to true. When you find a dot you set it to false. If you find a closing parenthesis and your variable is true you can abort, because your structure is broken.

Regular expression to allow only negative number

This sounds like it would be a fairly common issue, but I've searched a lot and can't find anything that works. I'm using the jquery validate plug-in to validate form input. There's a field which needs to accept only negative numbers (can be whole integers or decimals but must be less than zero).
I've tried doing something like this:
$.validator.addClassRules("negativeNumber", { range: [-1000000000, 0] });
...which works okay, but the validation error is horrible ("Please enter a number between -1000000000 and 0") - I'd like it to just say "Please enter a negative number".
Could anyone point me in the direction of a regex that only allows negative numbers?
Many thanks folks...
Instead of a regex, you can add a custom validation method, which I believe is easier to read.
$.validator.addMethod('negativeNumber',
function (value) {
return Number(value) < 0;
}, 'Enter a negative number');
I would think \-\d*(\.?\d+) would do it.
\- matches a minus
\d* matches zero or more digits (to account for things like -.5)
\.? matches a decimal point if it's there
\d* matches zero or more digits
This will match anything less than 0 \-\d*(\.\d+)?
Including -.00001, -100000, and -1
This would be so much easier with a custom validation method:
jQuery.validator.addMethod('negativeNumber', function(value, element) {
return this.optional(element) || (+value < 0);
}, 'Please enter a negative number');
That is much nicer (and probably quicker) than regex, and let's the browser parse the number for you, rather than doing it yourself with regex.
Or, of course, use the max method, although the message there isn't quite as nice.