regular expression for validating fields - javascript

Validations i'm trying :
regular expression of : 9999.99 and no spaces (0009.99 it should convert 9.99
Edit :
var regex = '(?!0)\d+(?:\.\d+)?$';
function getValue() {
// passing value 0009.99 and 0009.00 and 100
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}

Your first and second seems to Work just fine, the third can be achieved with the following regex:
/(?!0)\d+\.\d+$/
It starts by looking forward for zeros (skipping them), then it matches any number of digits followed by a dot and more digits. If you want the digits to be optional you can replace the plus '+' with a star '*'.
Edit:
If you want to allow integers, you can use this regex:
/(?!0)\d+(?:\.\d+)?$/
That makes the dot and the digits after that optional.
BTW: Your jsfiddle does not help in answering.
Edit2:
To create a Regex using quotes you must use the following syntax:
var regex = new RegExp('(?!0)\d+(?:\.\d+)?$');
Edit3:
I forgot to mention, you need to double escape backslashes, it should be:
var regex = new RegExp('(?!0)\\d+(?:\\.\\d+)?$');
Now it should Work directly in your code.

Related

Regex replace not removing characters properly

I have the regular expression:
const regex = /^\d*\.?\d{0,2}$/
and its inverse (I believe) of
const inverse = /^(?!\d*\.?\d{0,2}$)/
The first regex is validating the string fits any positive number, allowing a decimal and two decimal digits (e.g. 150, 14., 7.4, 12.68). The second regex is the inverse of the first, and doing some testing I'm fairly confident it's giving the expected result, as it only validates when the string is anything but a number that may have a decimal and two digits after (e.g. 12..05, a5, 54.357).
My goal is to remove any characters from the string that do not fit the first regex. I thought I could do that this way:
let myString = '123M.45';
let fixed = myString.replace(inverse, '');
But this does not work as intended. To debug, I tried having the replace character changed to something I would be able to see:
let fixed = myString.replace(inverse, 'ZZZ');
When I do this, fixed becomes: ZZZ123M.45
Any help would be greatly appreciated.
I think I understand your logic here trying to find a regex that is the inverse of the regex that matches your valid string, in the hopes that it will allow you to remove any characters that make your string invalid and leave only the valid string. However, I don't think replace() will allow you to solve your problem in this way. From the MDN docs:
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
In your inverse pattern you are using a negative lookahead. If we take a simple example of X(?!Y) we can think of this as "match X if not followed by Y". In your pattern your "X" is ^ and your "Y" is \d*\.?\d{0,2}$. From my understanding, the reason you are getting ZZZ123M.45 is that it is finding the first ^ (i.e, the start of the string) that is not followed by your pattern \d*\.?\d{0,2}$, and since 123M.45 doesn't match your "Y" pattern, your negative lookahead is satisfied and the beginning of your string is matched and "replaced" with ZZZ.
That (I think) is an explanation of what you are seeing.
I would propose an alternative solution to your problem that better fits with how I understand the .replace() method. Instead of your inverse pattern, try this one:
const invalidChars = /[^\d\.]|\.(?=\.)|(?<=\.\d\d)\d*/g
const myString = '123M..456444';
const fixed = myString.replace(invalidChars, '');
Here I am using a pattern that I think will match the individual characters that you want to remove. Let's break down what this one is doing:
[^\d\.]: match characters that are not digits
\.(?=\.): match . character if it is followed by another . character.
(?<=\.\d\d)\d*: match digits that are preceded by a decimal and 2 digits
Then I join all these with ORs (|) so it will match any one of the above patterns, and I use the g flag so that it will replace all the matches, not just the first one.
I am not sure if this will cover all your use cases, but I thought I would give it a shot. Here's a link to a breakdown that might be more helpful than mine, and you can use this tool to tweak the pattern if necessary.
I don't think you can do this
remove any characters from the string that do not fit the first regex
Because regex matching is meant for the entire string, and replace is used to replace just a PART inside that string. So the Regex inside replace must be a Regex to match unwanted characters only, not inverted Regex.
What you could do is to validate the string with your original regex, then if it's not valid, replace and validate again.
//if (notValid), replace unwanted character
// replace everything that's not a dot or digit
const replaceRegex = /[^\d.]/g; // notice g flag here to match every occurrence
const myString = '123M.45';
const fixed = myString.replace(replaceRegex, '');
console.log(fixed)
// validate again

javascript regular expression not working

I am trying to validate a textbox to ensure that a URL is written inside (minus the "http://" part). Here is my code:
var isUrl;
var regex = new RegExp("^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)");
var siteUrl = e.target.value;
if (siteUrl.match(regex)) {
isUrl = true;
}
else {
isUrl = false;
}
So my regular expression is ^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?).
I was under the impression that this would do the following:
NOT match anything beginning with http.. which it does correctly
Allow an optional www. at the start
Accept 1 or more characters from a-z to be typed in
Accept a dot after those characters
Accept 2 or more characters following the dot, and
Allow an optional dot followed by two or more characters again.
In practice, the textbox accepts strings like "ashdiguasdf" and "aksjdnfa:://',~" which it should not do. Can anyone explain why?
The main problem is that you're using the \ character in a quoted string, which javascript will interpret as the start of a "control character" (such as \n for a newline, etc).
One option is to escape it by replacing \ with \\.
But the easiest solution is to use the following format...
var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/);
This also allows you to make it case insensitive (if you wish) by using the i character at the end, like this...
var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/i);
As an extra bit, you're using more capture groups than really necessary. Your expression could also be written like this with the same result...
^(?!http)(?:www\.)?[a-z]+(?:\.[a-z]{2,}){1,2}

Regular expression in jquery allow only one match

Okay, i've got the following problem. I used jquery to test a string with a regular expression. It works all fine, but....
In the Netherlands the zipcodes are 4 digits followed by 2 characters e.g. 1234AB.
Now i use the following regex to find this: [0-9]{4}[A-Z]{2}.
But when someone types 1234AB+948203848 for example. It also return true. And i don't want that! How can i make it return false when it's not 4 digits followed by 2 characters?
Thanks in advance.
JSBIN
Use anchors ^ and $. So your regex would become:
/^\d{4}[A-Z]{2}$/
Just use anchors to indicate the beginning of the word (^) and the end of it ($):
var patt = new RegExp("^[0-9]{4}[A-Z]{2}$");
^ ^
As per your comments, you also want to capitalize the input. For this, you can use .toUpperCase():
Test ---> JSBIN
$(document).ready(function(){
$('[name=postcode]').keyup(function(){
var str = $(this).val().toUpperCase();
var patt = new RegExp("^[0-9]{4}[A-Z]{2}$");
var res = patt.test(str);
console.log(res);
});
});
Alternatively, you can use ^[0-9]{4}[a-zA-Z]{2}$ (note the [a-zA-Z] part) to check the four letters, no matter upper or lowercase.

Regex with numerics and dashes only

I am facing an issue in JavaScript form validation. I have to store number in this format 1-74347064527
I have tried these regular expressions but not worked properly:
var srNo =/^[-0-9]*$/;
var srNo = /^[0-9]+(-[0-9]+)+$/;
var srNo=/^([0-9]+-)*[0-9]+$/;
Suggest some regex for this.
Kind regards.
This should work unless you have additional constraints:
var srNo = /^\d+-\d+$/;
If you prefer the [0-9] syntax:
var srNo = /^[0-9]+-[0-9]+$/;
When in a character class ([ ]), dash ( - ) has a special meaning in regular expressions - it means "range", eg. a-z means from 'a' to 'z'. You're not escaping it, so your RegExps are not even correct (at least not in every language).
Update: It appears, that this syntax is correct when dash is not surrounded by other characters (when it's placed at the beginning or end of the character class). Sorry for confusion.
Try this instead:
/^\d\-\d+$/
It matches strings that begin with one digit, followed by a dash, and then by one or more digits.
var regex = /^\d{1}-?\d{11}$/g
window.alert(regex.test('1-74347064527'));

javascript regex for special characters

I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}

Categories