This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
UK Postcode Regex (Comprehensive)
I have the following code for validating postcodes in javascript:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
return regex.test(postcode);
}
Tests:
CF47 0HW - Passes - Correct
CF47 OHW - Passes - Incorrect
I have done a ton of research but can't seem to find the definitive regex for this common validation requirement. Could someone point me in the right direction please?
Make your regex stricter by adding ^ and $. This should work:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
}
You want a 'definitive regex' - given all the permutations of the UK postcodes, it needs to be therefore 'unnecessarily large'. Here's one I've used in the past
"(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})"
Notice I never just use A-Z, for instance, because in each part there are always certain letters excluded.
The problem is the first line of your function. By trimming the spaces out of the target string, you allow false positives.
CF47OHW will match [A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}
CF matches [A-Z]
4 matches [0-9]{1,2}
(blank) matches \s?
7 matches [0-9]
OH matches [A-Z]{2}
W gets discarded
So, as Paulgrav has stated, adding the start and end characters (^ and $) will fix it.
At that point, you can also remove the \s? bit from the middle of your regex.
However! Despite the bug being fixed, your regex is still not going to work how you'd like it to. You should look at the following rather good answer on this here site UK Postcode Regex (Comprehensive)
Related
I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value. This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs. My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?
What I tried was mutating the:
/#(\d|\w){3}{6}/
Regular expression to this:
/#(\d|\w){3|6}/
Obviously this didn't work. I realize I could write:
/(#(\d|\w){3})|(#(\d|\w){6})/
However I'm hoping for something that looks better.
The shortest I could come up with:
/#([\da-f]{3}){1,2}/i
I.e. # followed by one or two groups of three hexadecimal digits.
You can use this regex:
/#[a-f\d]{3}(?:[a-f\d]{3})?\b/i
This will allow #<3 hex-digits> or #<6 hex-digits> inputs. \b in the end is for word boundary.
RegEx Demo
I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (i.e. #FFF5 / #FFFFFF55). Which made things a little more complicated as the valid combinations goes up a little.
In case it's of any use, here's what I came up with:
var inputs = [
"#12", // Invalid
"#123", // Valid
"#1234", // Valid
"#12345", // Invalid
"#123456", // Valid
"#1234567", // Invalid
"#12345678", // Valid
"#123456789" // Invalid
];
var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;
inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));
Which should return:
#123 valid
#1234 valid
#12345 -
#123456 valid
#1234567 -
#12345678 valid
#123456789 -
I am trying to verify str with the code below. My final goal is to allow this style of input:
18.30 Saturday_lastMatch 3/10
However, the code I have can't even work for the basic usage (98.5% str will be of this format):
19.30 Friday 15/5
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]\/[0-9]{2}/;
if(!str.match(regex)) {
//"Bad format, match creation failed!");
}
What am I missing?
There are a number of problems with your regex.
The date & time matching portions at the beginning and end don't allow for 1 or 2 digit numbers as they should.
You may want to consider anchoring the regex at the beginning and end with ^ and $, respectively.
The literal dot in the character class doesn't need to be escaped.
Try this:
var regex= /^[0-9]{1,2}[.:][0-9]{1,2} [A-Z][a-z]{5,8} [0-9]{1,2}\/[0-9]{1,2}$/;
The final part of your regular expression that checks day/month needs to be expanded. It currently only matches #/##, but it should allow ##/# as well. The simplest fix would be to allow either one or two digits on either side (e.g. 12/31)
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]{1,2}\/[0-9]{1,2}/;
My question is simple but takes work. I tried lots of regex expressions to check my datetime is ok or not, but though I am sure my regex exprerssion is correct it always return to me isnotok with ALERT. Can you check my code?
validateForLongDateTime('22-03-1981')
function validateForLongDateTime(date){
var regex=new RegExp("/^\d{2}[.-/]\d{2}[.-/]\d{4}$/");
var dateOk=regex.test(date);
if(dateOk){
alert('ok');
}else{
alert('notok');
}
}
There are at least 2 issues with the regex:
It has unescaped forward slashes
The hyphen in the character classes is unescaped and forms a range (matching only . and /) that is not what is necessary here.
The "fixed" regex will look like:
/^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/
See demo
However, you cannot validate dates with it since it will also match 37-67-5734.
Here is an SO post with a comprehensive regex approach that looks viable
Here is my enahanced version with a character class for the delimiter:
^(?:(?:31([\/.-])(?:0?[13578]|1[02]))\1|(?:(?:29|30)([\/.-])(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29([\/.-])0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])([\/.-])(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Here is an SO post showing another approach using Date.parse
this way you can validate date between 1 to 31 and month 1 to 12
var regex = /^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d$/
see this demo here https://regex101.com/r/xP1bD2/1
below is a my attempt at a function to validate a form field with the prefix ZHA or zha followed by 6 numbers. The prefix part seems to be working but if I enter 1 number it still validates. Any suggestions?
function checkHnum(hnumvalue){
var authTest = /^[ZHA]|[zha]+[\d]{6}$/;
return authTest.test(hnumvalue)
}
Thanks.
Your regex doesn't accept 1 digit only but it's buggy as it, for example, doesn't constraint the order of the letters ([ZHA] is "Z or H or A"). You seem to want
var ok = /^(ZHA|zha)\d{6}$/.test(yourString)
Note that if you also want to accept "Zha123456" then you can simply use a case insensitive regular expression :
var ok = /^zha\d{6}$/i.test(yourString)
Your regex should be:
/^ZHA\d{6}$/i
Note the i to make it case insensitive. The problem with yours was mainly the brackets. The brackets match one of the characters that inside of it.
For example
[ZHA] will match Z, or H, or A, but not the full ZHA
Hope this helps. Cheers
I have a regex which allows only to enter integers and floats in a text box.
Regex Code:-
("^[0-9]*(?:[.][0-9]*|)$");
But it gives an error when the user enters whitespace at the beginning and end of the entered values. I want the user to allow spaces at the beginning and at the end as optional, so I changed the regex as below but it didn't work.
Note: Spaces may be spaces or tabs.
Test Case: User might enter:
"10","10.23"," 10","10 "," 10.23","10.23 "
Any number of spaces are allowed.
("^(?:\s)*[0-9]*(?:[.][0-9]*|)$")
I am newbie with regex, so any help will be highly appreciated.
Thank you.
Try this:
/^\s*[0-9]*(?:[.][0-9]*|)\s*$/;
You don't have to wrap a single entity in a group to repeat it, and I have added a second zero-or-more-spaces at the end which is what you are missing to make it work.
Note: You have not posted the code you use to create the RegExp object, but if it is new RegExp(string), remember to escape your backslashes (by doubling them):
var r = new RegExp("^\\s*[0-9]*(?:[.][0-9]*|)\\s*$");
Also, as #Blender suggests, this can be simplified to:
/^\s*[0-9]*(?:\.[0-9]*)?\s*$/;
Or, using \d instead of [0-9]:
/^\s*\d*(?:\.\d*)?\s*$/;
You don't necessarily need a Regular Expression: !isNaN(Number(textboxvalue.trim())) would be sufficient.
Otherwise, try /^\s{0,}\d+\.{0,1}\d+\s{0,}$/. Test:
var testvalues = ["10","10.23"," 10","10 "," 10.23","10.23 ","10.24.25"];
for (var i=0;i<testvalues.length;i+=1){
console.log(/^\s{0,}\d+\.{0,1}\d+\s{0,}$/.test(testvalues[i]));
}
//=> 6 x true, 1 x false