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.
Related
I have a string to replace semi-colons with \n. The requirement I have is to detect only those semi-colons that are outside HTML <> tags and replace them with \n.
I have come very close by using this regex by implementing multiple fixes.
/((?:^|>)[^<>]*);([^<>]*(?:<|$))/g, '$1\n$2'
The above regex works well if I input string like the below one -
Value1;<p style="color:red; font-weight:400;">Value2</p>;<p style="color:red; font-weight:400;">Value3</p>;Value4
The output it gives is this (which is expected and correct) -
Value1
<p style="color:red; font-weight:400;">Value2</p>
<p style="color:red; font-weight:400;">Value3</p>
Value4
But fails if I input string like - M1;M2;M3
The output this gives is -
M1;M2
M3
(semi-colon doesn't remove between M1 and M2).
whereas the expected output should be -
M1
M2
M3
Also the string can be like this too (both combined) - M1;M2;M3;Value1;<p style="color:red; font-weight:400;">Value2</p>;<p style="color:red; font-weight:400;">Value3</p>;Value4
The major goal is to replace all the semicolons outside HTML Tags <> and replace it with '\n` (enter key).
You can use this regex associate with .replace() function of JavaScript:
/(<[^<>]*>)|;/g
For substitution, you may use this function:
(_, tag) => tag || '\n'
If (<[^<>]*>) catches anything - which is a HTML tag, it will go into tag parameter, otherwise an outbound ; must be matched.
So you can check if tag exists. If it exists, replace with itself, otherwise replace it with a \n.
const text = `Value1;<p style="color:red; font-weight:400;">Value2</p>;<p style="color:red; font-weight:400;">Value3</p>;Value4
M1;M2;M3`;
const regex = /(<[^<>]*>)|;/g;
const result = text.replace(regex, (_, tag) => tag || '\n');
console.log(result);
var str = `
<br><br/>
<Br>
foobar
<span>yay</span>
<br><br>
catmouse
<br>
`;
//this doesn't work but what I have so far
str.replace(/^(<br\s*\/?>)*|(<br\s*\/?>)*$/ig, '');
var desiredOutput = `
foobar
<span>yay</span>
<br><br>
catmouse
`;
I want to ensure that I remove all <br>'s regardless of case or ending slash being present. And I want to keep any <br>'s that reside in the middle of the text. There may be other html tags present.
Edit: I want to note that this will be happening server-side so DOMParser won't be available to me.
We may try using the following pattern:
^\s*(<br\/?>\s*)*|(<br\/?>\s*)*\s*$
This pattern targets <br> tags (and their variants) only if they occur at the start or end of the string, possibly preceded/proceeded by some whitespace.
var str = '<br><br/>\n<Br>\nfoobar\n<span>yay</span>\n<br><br>\ncatmouse\n<br>';
console.log(str + '\n');
str = str.replace(/^\s*(<br\/?>\s*)*|(<br\/?>\s*)*\s*$/ig, '');
console.log(str);
Note that in general parsing HTML with regex is not advisable. But in this case, since you just want to remove flat non-nested break tags from the start and end, regex might be viable.
Don't use a regular expression for this - regular expressions and HTML parsing don't work that well together. Even if it's possible with a regex, I'd recommend using DOMParser instead; transform the text into a document, and iterate through the first and last nodes, removing them while their tagName is BR (and removing empty text nodes too, if they exist):
var str = `
<br><br/>
<Br>
foobar
<span>yay</span>
<br><br>
catmouse
<br>
`;
const body = new DOMParser().parseFromString(str.trim(), 'text/html').body;
const nodes = [...body.childNodes];
let node;
while (node = nodes.shift(), node.tagName === 'BR') {
node.remove();
const next = nodes[0];
if (next.nodeType === 3 && next.textContent.trim() === '') nodes.shift().remove();
}
while (node = nodes.pop(), node.tagName === 'BR') {
node.remove();
const next = nodes[nodes.length - 1];
if (next.nodeType === 3 && next.textContent.trim() === '') nodes.pop().remove();
}
console.log(body.innerHTML);
Note that it gets a lot easier if you don't have to worry about empty text nodes, or if you don't care about whether there are empty text nodes or not in HTML output.
Try
/^(\s*<br\s*\/?>)*|(<br\s*\/?>\s*)*$/ig
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
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
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.