regex validation in javascript - javascript

Question:
Maximum of 5 characters (0.000 < courier weight <=5.000 with max of 3 digits after decimal point)
Values can be between 0 and 5. Excluding 0 and including 5.
My codes:
function checkWeightOfParcel(weightOfParcel) {
var regex=/^[0-5]+\.[0-9]$/;
if(regex.test(weightOfParcel)) {
alert('correct!!!')
return true;
}
else {
alert('wrong regex!')
return false;
}
}
*my code only can validate range 0.000 to 5.999, it is wrong. How to remove 0.999 behind to set the max value is 5.000
Any website or forum to learn javascript regex? i'm new to it, thanks for help.

No reason to use regex for this. Parse it to a number using parseFloat, and then use simple conditions:
function checkWeightOfParcel(weightOfParcel) {
//Turn it into a number
weightOfParcel = parseFloat(weightOfParcel);
if (weightOfParcel > 0 && weightOfParcel <= 5) {
alert('correct!!!')
return true;
}
else {
alert('wrong regex!')
return false;
}
}

You shouldn't be using regex to do this. Simple code check like this is suffice:
if(weightOfParcel > 0 && weightOfParcel <= 5) {
alert('correct!!!')
return true;
}
else {
alert('wrong value!')
return false;
}

While you shouldn't use regexp for this, here is one that works:
/^(?:(?:[1-4](?:\.\d{1,3})?)|(?:5(?:\.0{1,3})?)|(?:0\.(?:(?:(?:[1-9]\d{0,2}))|(?:0[1-9]\d?)|(?:00[1-9]))))$/
A site that is great for trying out and understanding regex is this one (already filled with your regex):
http://regex101.com/r/cM6xC9
Basically, i split your cases in two:
Numbers starting with 1,2,3,4 which may be followed by a . followed by 1,2 or 3 decimals.
Numbers starting with 5 which may be followed by a . followed by 1,2 or 3 zeroes.
Numbers starting with 0 which must be followed by a . followed by
non zero digit followed by 0-2 more digits
0 followed by non zero digit followed by 0-1 more digits
00 followed by non zero digit

Another bad idea :D
/^((?!0(\.0{1,3})?$)[0-4](\.\d{1,3})?|5(\.0{1,3})?)$/
http://regex101.com/r/kV5qK0

Why are you using regex? it is easier to compare numbers.
function checkWeightOfParcel(weightOfParcel) {
// var weightOfParcel = parseFloat(weightOfParcel); // to avoid double parsing
return parseFloat(weightOfParcel) < 0 || parseFloat(weightOfParcel) > 5
}

Related

Regular expression for GST Identification Number (GSTIN)

What is the regex for the GST number in India?
You can read more about the GST numbers in What is GST Number? – Know your 15 Digits GSTIN. On a summary level, the number is represented as
List item. The first two digits of this number will represent the state code as per 2011 Census of India
The next ten digits will be the PAN number of the taxpayer
The thirteenth digit will be assigned based on the number of registration within a state
The fourteenth digit will be Z by default
The last digit will be for a check code
Here is the regex and checksum validation for GSTIN:
\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}[Z]{1}[A-Z\d]{1}
Format details
The first two digits of the GST Number will represent the State Code as per the Census (2011).
The next 10 digits will be same as in the PAN number of the taxpayer.
The first five will be alphabets
The next four will be numbers
The last will be the check code
The 13th digit will be the number of registrations you take within a state, i.e., after 9, A to Z are considered as 10 to 35.
The 14th digit will be Z by default.
The last would be the check code.
Here is the code for verifying/validating the GSTIN number using the checksum in JavaScript
function checksum(g){
let regTest = /\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}[Z]{1}[A-Z\d]{1}/.test(g)
if(regTest){
let a=65,b=55,c=36;
return Array['from'](g).reduce((i,j,k,g)=>{
p=(p=(j.charCodeAt(0)<a?parseInt(j):j.charCodeAt(0)-b)*(k%2+1))>c?1+(p-c):p;
return k<14?i+p:j==((c=(c-(i%c)))<10?c:String.fromCharCode(c+b));
},0);
}
return regTest
}
console.log(checksum('27AAPFU0939F1ZV'))
console.log(checksum('27AASCS2460H1Z0'))
console.log(checksum('29AAGCB7383J1Z4'))
GST regex and checksum in various programming languages
Here is the regex that I came up with:
/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/
According to H&R Block India GSTIN guide, the 13th 'digit' (entity code) is "an alpha-numeric number (first 1-9 and then A-Z)". That is, zero is not allowed and A-Z represent 10-35. Hence the [1-9A-Z] is more accurate than [0-9].
The last digit, "check digit", is indeed alphanumeric: [0-9A-Z]. I have independently confirmed by obtaining and testing actual GSTINs.
The correct validation for GSTIN should be
^([0][1-9]|[1-2][0-9]|[3][0-7])([a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9a-zA-Z]{1}[zZ]{1}[0-9a-zA-Z]{1})+$
The first 2 digits denote the State Code (01-37) as defined in the Code List for Land Regions.
The next 10 characters pertain to PAN Number in AAAAA9999X format.
13th character indicates the number of registrations an entity has within a state for the same PAN.
14th character is currently defaulted to "Z"
15th character is a checksum digit
This regex pattern accommodates lower and upper case.
To add to the previous answers, this answer also provides a code snippet for the checksum digit.
public static final String GSTINFORMAT_REGEX = "[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9a-zA-Z]{1}";
public static final String GSTN_CODEPOINT_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String getGSTINWithCheckDigit(String gstinWOCheckDigit) throws Exception {
int factor = 2;
int sum = 0;
int checkCodePoint = 0;
char[] cpChars;
char[] inputChars;
try {
if (gstinWOCheckDigit == null) {
throw new Exception("GSTIN supplied for checkdigit calculation is null");
}
cpChars = GSTN_CODEPOINT_CHARS.toCharArray();
inputChars = gstinWOCheckDigit.trim().toUpperCase().toCharArray();
int mod = cpChars.length;
for (int i = inputChars.length - 1; i >= 0; i--) {
int codePoint = -1;
for (int j = 0; j < cpChars.length; j++) {
if (cpChars[j] == inputChars[i]) {
codePoint = j;
}
}
int digit = factor * codePoint;
factor = (factor == 2) ? 1 : 2;
digit = (digit / mod) + (digit % mod);
sum += digit;
}
checkCodePoint = (mod - (sum % mod)) % mod;
return gstinWOCheckDigit + cpChars[checkCodePoint];
} finally {
inputChars = null;
cpChars = null;
}
}
Sources:
GST Google Group Link,
Code Snippet Link
This is a 100% accurate regex of GSTIN, as it checks everything mentioned in the above image.
[0-9]{2}[A-Z]{3}[ABCFGHLJPTF]{1}[A-Z]{1}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}
Try this one with jQuery
$(document).ready(function() {
$.validator.addMethod("gst", function(value3, element3) {
var gst_value = value3.toUpperCase();
var reg = /^([0-9]{2}[a-zA-Z]{4}([a-zA-Z]{1}|[0-9]{1})[0-9]{4}[a-zA-Z]{1}([a-zA-Z]|[0-9]){3}){0,15}$/;
if (this.optional(element3)) {
return true;
}
if (gst_value.match(reg)) {
return true;
} else {
return false;
}
}, "Please specify a valid GSTTIN Number");
$('#myform').validate({ // initialize the plugin
rules: {
gst: {
required: true,
gst: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<form id="myform" action="" method="post">
<div>
<label>GSTTIN #</label>
<div>
<input type="text" name="gst" value="" id="input-gst" />
</div>
</div>
<button type="submit">Register</button>
</form>
I used this one and checked it against 30+ GSTINs, and it worked flawlessly.
/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/
The last check digit also seems to be alphanumeric in some of the GSTINs I came across.
Try this.
It is working as per GSTIN.
^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$
The correct regex for GSTIN is as:
^([0][1-9]|[1-2][0-9]|[3][0-7])([A-Z]{5})([0-9]{4})([A-Z]{1}[1-9A-Z]{1})([Z]{1})([0-9A-Z]{1})+$
It is correct and have been applied to more than 300 valid taxpayers whom you can validate from this link.
The regex should be:
/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[0-9]{1}Z[0-9]{1}$/
The correct regex could be:
/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[0-9]{1}Z[0-9]{1}?$/
It works for me.
My working regex is
/^([0][1-9]|[1-2][0-9]|[3][0-8])[A-Z]{3}[ABCFGHLJPTF]{1}[A-Z]{1}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}/
According to 38 States as of the year 2021.
Correct GSTIN validation will be covering 27 states of India,
^([0][1-9]|[1-2][0-9]|[3][0-7])([a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9a-zA-Z]{1}[zZ]{1}[0-9a-zA-Z]{1})+$
If you want a Node.js library, you can use GSTIN Validator:
var validator = require('gstin-validator');
validator.isValidGSTNumber('12AAACI1681G1Z0'); // Returns a Boolean value.
validator.ValidateGSTIN('47AAACI1681G1Z0'); // Returns a response string with an error message
validator.getGSTINInfo('12AAACI1681G1Z0'); // Returns metadata for GSTIN based on the followed numbering scheme.

How to check if a string is a positive integer, allowing 0 and all-0 decimals

So to check if a string is a positive integer, I have done some research and found this solution here by someone:
Validate that a string is a positive integer
function isNormalInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
However, I put this into test, and found that numbers with pure 0's on the decimal places does not seem to be working. For example:
15 ===> Works!
15.0 ====> Does not work :(
15.000 ===> Does not work :(
Build upon the existing method, how could I allow pure-0's on the decimal places and make them all work? Please note 15.38 should not work, but 15.00 should.
No need to use regex here.
function isNormalInteger(str) {
var n = parseInt(str);
return n > 0 && n == +str;
}
Then test it:
isNormalInteger(15)
true
isNormalInteger(15.00)
true
isNormalInteger(15.38)
false
isNormalInteger(-15)
false
isNormalInteger(-15.1)
false
First of all the function should be called isNormalNumber instead of isNormalInteger as it accepts decimals, then this is the REgex you need:
function isNormalNumber(str) {
return /^\+*[0-9]\d*(\.0+)?$/.test(str);
}
alert(isNormalNumber("+10.0") + "::" + isNormalNumber("+10.9") + "::" + isNormalNumber("10"));
Returns true::false:true.
EDIT:
This is an edit to avoid matching leading zeros like in the numbers 001234 and 07878:
^\+*[1-9]\d*(\.0+)?$|^0(\.0+)?$
Quick and dirty
function isNormalInteger(str) {
var ival=parseInt(str);
return ival!=NaN && ival>=0 && ival==parseFloat(str);
}

Regular expression in Javascript for a string which have ONLY numbers & should not have any characters at any position except numbers

Problem is: I have one text area in jsp file, from here I am reading value through javascript and validating if the entered value is a "number between 1-25". Below is my explanation.
1) My string should contain only number between [1-25]
2) It should not have any of the characters (spl chars/symbols) apart from numbers [1-25] at any position in the string.
for example:
12-allowed (less than 25 and greater than 1) show success_message
1##4- not allowed, show warn_message
#14#- not allowed, show warn_message
!$%12()*& - not allowed even though number is less than 25 and greater than 1, since it contains characters apart from numbers, show warn_message.
This is what i have tried
File.jsp
<div class="row">
<div class="large-1 columns">
<input id="text_area" name="posArea" type="text"/>
</div>
</div>
MyFile.js
<script>
var pos= ($('#text_area').val());
var reg="^[1-25]$";
if(pos.match(reg)){
$('#warn_message').show();
return false;
}
if(isNaN(pos)){
$('#warn_message').show();
return false;
}
else{
$('#success_message').show();
}
</script>
This is showing warning message for any number I enter, Can anyone spot my mistake? Thanks for any help. Please comment in case you do not understand my question
^(?:[1-9]|1\d|2[0-5])$
Try this.See demo.
https://regex101.com/r/sJ9gM7/17
[1-25] does not mean a range from 1 to 25.It means a range from 1 to 2 and 5 in a character class.
The regex [1-25] matches 1, 2, 5, 1 time exactly.
For whole numbers, you can use this regex: ^(?:2[0-5]|[1][0-9]|[1-9])$
It will not fractions, but I think you are not interested in them.
See demo.
You can do that without Regex :
function checkNumber(number) {
if(isNaN(number)) {
return false;
} else {
number = parseInt(number)
return number > 1 && number < 25
}
}

How to create regex for passwords validate with length 8 - 24 and contain at least 3 of the following: lowercase, uppercase, numbers, special char

I want to use java-script to validate following criteria for password.
a.A password of at least 8 and no more than 24 characters is required.
b.Every password must contain at least three of these four types of characters:
1.an upper case letter
2.a lower case letter
3.a number
4.a special character.
I have found this code which is really easy and hand-full but it is just checking all 4 conditions not just at-least 3 conditions out of 4.
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,24}"
I will really appreciate if you help me to figure out to create javascript validation on password to full fill my above requirement.
Thank you all for your help. I have modified #Ehtesham code and achieved the functionality.
function isValidPassword(pass) {
var lowerRegex = /[a-z]/;
var upperRegex = /[A-Z]/;
var numberRegex = /[0-9]/;
var specialRegex = /[$#$!%*?&]/;
var count = 0;
if (pass.length < 8 || pass.length > 24) {
return false;
}
if (pass.match(lowerRegex)){count += 1;}
if (pass.match(upperRegex)){count += 1;}
if (pass.match(numberRegex)){count += 1;}
if (pass.match(specialRegex)){count += 1;}
if (count >= 3){
return true;
}else{
return false;
}
}
The regex you provided is made out of 5 major parts:
The pattern validating the length: [A-Za-z\d$#$!%*?&]{8,24}
A positive lookahead for at least one lowercase: (?=.*[a-z])
A positive lookahead for at least one uppercase: (?=.*[A-Z])
A positive lookahead for at least one number: (?=.*\d)
A positive lookahead for at least one special char: (?=.*[$#$!%*?&])
Now, you only want to apply 3 out of the 4 positive lookaheads. Since lookaheads are non-consuming matches, the cursor of the regex-engine will remain unchanged, as the matching is going on. (Using positive Lookaheads this way is often used to generate AND-Patterns)
So, you now have 4 conditions and you want that only 3 of them are matched. As described, it would be easy to use independent expressions and check if 3 apply. However, some native features (for instance jsf's f:validateRegex) only work with a single pattern.
Regular Expressions are supporting OR in a native way: | - hence to turn your expression 1 AND 2 AND 3 AND 4 into a minimum requirement of matching 3 of them, you could use an expression like (1 AND 2 AND 3) OR (1 AND 2 AND 4) OR (1 AND 3 AND 4) OR (2 AND 3 AND 4), which would cover all usecases required:
1 2 3 4
1 1 1 0
1 1 0 1
1 0 1 1
0 1 1 1
So, to match all this within a single pattern, just rearange your lookaheads as required:
^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])|(?=.*[a-z])(?=.*\d)(?=.*[$#$!%*?&])|(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&]))[A-Za-z\d$#$!%*?&]{8,24}$
Drilldown:
^(?: - non matching group
(?=.*[a-z])(?=.*[A-Z])(?=.*\d) - one lower, one upper, one number
| - or
(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&]) - one lower, one upper, one special
| - or
(?=.*[a-z])(?=.*\d)(?=.*[$#$!%*?&]) - one lower, one number, one special
| - or
(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&]) - one upper, one number, one special
)
[A-Za-z\d$#$!%*?&]{8,24}$ - 8 to 24 chars.
(Debuggex is using javascript)
^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])|(?=.*[a-z])(?=.*\d)(?=.*[$#$!%*?&])|(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&]))[A-Za-z\d$#$!%*?&]{8,24}$
Debuggex Demo
Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference. There is a password validation entry under
"Common validation tasks > Internet"
That said, this seems like a pretty easy task if you break it up, as others have suggested. Mashing up all those requirements into a single regex, although an interesting exercise, is overkill in my opinion.
(This is Java, but there are equivalent concepts in JavaScript.)
public bolean isPasswordValid(String password) {
if(!length in bounds) {
return false;
}
boolean hasUpper = Pattern.compile("[a-z]").find(password);
boolean hasLower = Pattern.compile("[A-Z]").find(password);
boolean hasDigit = Pattern.compile("[0-9]").find(password);
boolean hasSpecialChar = Pattern.compile("...NOT SURE OF THIS ONE...").find(password);
int types = (hasUpper ? 1 : 0) + (hasLower ? 1 : 0) +
(hasDigit ? 1 : 0) + (hasSpecialChar ? 1 : 0);
return (types >= 3);
}
And if this is a function that will be used rapid fire, then you'll likely want to pre-compile and store those Matchers.
In javascript you can use following simple function.
function isValidPassword(pass) {
var lowerRegex = /[a-z]/;
var upperRegex = /[A-Z]/;
var numberRegex = /[0-9]/;
var specialRegex = /[$#$!%*?&]/;
if (pass.length < 8 || pass.length > 24) {
return false;
}
if (pass.match(lowerRegex) && pass.match(upperRegex) &&
pass.match(numberRegex) && pass.match(specialRegex)) {
return true;
}
return false;
}
Jsfiddle demo
This builds on Ehtesham's answer to require 3 out of 4:
function isValidPassword(pass) {
var lowerRegex = /[a-z]/;
var upperRegex = /[A-Z]/;
var numberRegex = /[0-9]/;
var specialRegex = /[$#$!%*?&]/;
var mustBe3 = 0;
if(pass.length < 9 || pass.length > 24) { return false; }
if(pass.match(lowerRegex)) { mustBe3 ++; }
if(pass.match(upperRegex)) { mustBe3 ++; }
if(pass.match(numberRegex)) { mustBe3 ++; }
if(pass.match(specialRegex)){ mustBe3 ++; }
// for testing ...
if(window.console) console.log('pass: '+pass+' mustBe3: '+mustBe3);
if( mustBe3 >= 3 ) { return true; }
return false;
}

Javascript regex for amount

I'm trying to get a regex for an amount:
ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])
What I have is:
/^\d+\.\{0,1}+\d{0,2)+$/
...obviously not working. Examples of what I'm trying to do:
123 valid
123.00 valid
12.34.5 invalid
123.000 invalid
Trying to match an amount with or without the period. If the period is included, can only be once and no more than two digits after.
Make the decimal point and 1 or 2 digits after the decimal point into its own optional group:
/^\d+(\.\d{1,2})?$/
Tests:
> var re = /^\d+(\.\d{1,2})?$/
undefined
> re.test('123')
true
> re.test('123.00')
true
> re.test('123.')
false
> re.test('12.34.5')
false
> re.test('123.000')
false
Have you tried:
/^\d+(\.\d{1,2})?$/
The ? makes the group (\.\d{1, 2}) optional (i.e., matches 0 or 1 times).
Would something like this work?
// Check if string is currency
var isCurrency_re = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
return String(s).search (isCurrency_re) != -1
}

Categories