Reputation: 5770
I am creating a form, with warning elements. All works great but need to define my patterns better.
$("#postcode").inputNotes(
{
warning: {
pattern: /^[0-9]+$/,
type: 'note',
text: 'Only numbers, please ...',
inversedBehavior: true
}
}
);
$("#phone").inputNotes(
{
warning: {
pattern: /^[0-9]+$/,
type: 'note',
text: 'Only numbers, no spaces please ...',
inversedBehavior: true
}
}
);
Ok for the Postcode warning, I want the pattern to expect 4 numbers
For the Phone warning, I want the pattern to expect 10 numbers.
Any help appreciated.
Upvotes: 4
Views: 16002
Reputation: 287
just to save people time here is an example of how to use in jquery
$("#address-postal-code").once().on('blur', function (e) {
var myRegEx = new RegExp('^(0[289][0-9]{2})|([1-9][0-9]{3})$');
var ele = $(this);
if (!myRegEx.test(ele.val())) {
console.log('no good');
}
else {
console.log('good');
}
})
Upvotes: 0
Reputation: 11
All these answers are assuming that you limit the text field to 4 characters eg. (12345) is valid, to limit the length use the following
^(0[289][0-9]{2})$|^([1-9][0-9]{3})$
Upvotes: 1
Reputation: 271
Australia Post has greatly simplified the rules in 2019.
You now only need to account for the ranges:
0200 – 0299, 0800-0999 and 1000 – 9999
So the Regular Expression for Validating Australian Postcodes is just:
^(0[289][0-9]{2})|([1-9][0-9]{3})$
Upvotes: 11
Reputation: 3034
Here are the rules for Australian postcodes:
ACT: 0200-0299 and 2600-2639.
NSW: 1000-1999, 2000-2599 and 2640-2914.
NT: 0900-0999 and 0800-0899.
QLD: 9000-9999 and 4000-4999.
SA: 5000-5999.
TAS: 7800-7999 and 7000-7499.
VIC: 8000-8999 and 3000-3999.
WA: 6800-6999 and 6000-6799
Regular Expression: ^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$
Pass: 0200|||7312|||2415
Fail: 0300|||7612|||2915
Upvotes: 11
Reputation: 82933
Update:
For 6 digit or 10 digit numbers:
pattern: /^[0-9]{10}|[0-9]{6}$/,
For four digit Postcode: pattern: /^[0-9]{4}$/,
For 10 digit Phone number:
(if phone number can't start with 0)
pattern: /^[1-9][0-9]{9}$/,
(if phone number can start with 0)
pattern: /^[0-9]{10}$/,
Upvotes: 6
Reputation: 490433
For a 4 digit postcode, you can use /^\d{4}$/
.
For a 10 digit postcode, you can use /^\d{10}$/
.
Keep in mind some people will type spaces, parenthesis etc into the phone number. You should strip all non digits first before validating with /[^\d]+/g
.
Upvotes: 3
Reputation: 129079
Instead of using the +
modifier, try using {num}
, where num
is the number of instances of the previous atom you want.
Upvotes: 2