Regular expression to verify zip code and checking for invalid characters - javascript

I am trying to validate an input for zip codes, now this zip code should work for US, CANADA, UK, all the countries but omit any special characters, so i tried, checking for invalid characters first if that passes then i check for the zip code to either be US or if not just to make sure there are valid characters and not more than 8 (space in between them is ok as long as its now US(which includes - for 5 + 4)
The problem I am having is that 11215 for example is returning as false for the valid character validation and 11215## is returning false also.
Here are my regex:
var reg1 = /^[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]+$/;
var reg2 = /(^\d{5}$)|(^\d{5}-\d{4}$)|(([a-z0-9]{8})*$)/
var isOk = reg1.test("11215"); // returns false!
if(isOk)
{
isOk = isOk && reg2.test("11215");
}
var isOk2 = reg1.test("11215##"); // returns false also!
if(isOk2)
{
isOk2 = isOk2 && reg2.test("11215##");
}

The test for "bad chars", reg1 will always be false unless your string is made entirely of "bad chars". I don't think this is the behaviour you wanted.
var matchBad = /[^\s\da-z\-]/i;
// Match all non-whitespace, non-digit, non-alpabet, non-hyphen
if (false === matchBad.test("11215")) { // no bad chars detected
console.log('pass!');
// continue checking validity..
} else { // bad chars detected
console.log('fail!);
}

Your first regex is testing whether the entire string has those characters. If you want containment, remove the ^ and $ denoting the beginning and ending of your regex:
var reg1 = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/;
This may be only part of the problem but it should get you somewhere. Note I also removed the + since it really only needs to match one character to detect a bad character.
Also another note of design. Your regex that exactly matches the pattern should really be sufficient for testing this. I'm not quite familiar though with the third type of zip, but you might want to make it capture the entire string (with ^ and $)

Javascript should be like below
<script type="text/javascript">
function IsValidZipCode(zipcode) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
}
</script>
Zipcode text should be
<input id="zipcode" class="zipcode" type="text" placeholder="Your Zipcode?" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required >

Related

Auto Format text after entry in vuejs

I am trying to auto-format the postal code after entry by the user. The postal code rule is Please use the format A0A 0A0 or 12345. So if the user enters L9V0C7, it auto reformats to L9V 0C7 and when the postal code includes all digits like 12345, it stays as it is. The maxlength should be 6 when the postal code has numbers and alphabets and 5 when the postal code includes only numbers. Help me fix this handlePostalCode method.
The issue I am facing is when I enter L9V0, 0 disappears and I am not able to enter the postal code any further.
<v-text-field
label='Postal Code'
class="required"
v-model='postal_code'
required
#input="handlePostalCode"
validate-on-blur
:rules='postalCodeRules'>
</v-text-field>
postalCodeRules: [
value => /^[A-z]\d[A-z] \d[A-z]\d$|^\d\d\d\d\d$/.test(value) || 'Please use the format A0A 0A0 or 12345'
]
handlePostalCode() {
if (this.postal_code.match(/^[0-9]+$/) != null) {
var replacedInput = this.postal_code.replace(/\D/g, '').match(/(\d{0,3})(\d{0,2})/);
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + '' + replacedInput[2];
}
else {
var replacedInput = this.postal_code.match(/(\w{0,3})(\w{0,3})/);
console.log(replacedInput)
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + ' ' + replacedInput[2];
}
}
The problem is that when the space has been entered after the first three A0A characters, that the regular expression (\w{0,3})(\w{0,3}) cannot cross that space, and will match the empty string with the second capture group, losing out on anything else that follows.
I would suggest the following:
Make the distinction between the first and second postal code rule based on the first character only: if it is a digit, apply the first rule, if not, apply the second rule
The logic you have for the all-numbers case is overly complex: after having removed the non-digit characters, all that is left to do is to clip the string to at most 5 characters. You can use slice for that.
The logic for the second rule could first remove all non-alphanumeric characters (so also spaces would be removed)
Then it could remove any digit that follows immediately after a previous digit, and remove any letter that follows immediately after a previous letter
Finally it could clip the string to 6 characters, and inject the space if there are 4 or more characters.
Here is how your function would look:
function _handlePostalCode() {
this.postal_code = /^\d/.test(this.postal_code)
? this.postal_code.replace(/[^\d]/g, "")
.slice(0, 5)
: this.postal_code.replace(/\W/g, "")
.replace(/(\d)(?:\d+)|([A-Z])(?:[A-Z]+)/gi, "$1$2")
.slice(0, 6)
.replace(/^(...)(.)/, "$1 $2");
}

Validate number formats in a contact form (javascript)

I have a function to validate phone number in a contact form, but i need to be able to put in "xxx xxx xxxx" for example, and not just "xxxxxxxx"
The number format should be:
xxx xxx xxxx
xxx-xxx-xxxx
xxx.xxx.xxxx
function validatePhone() {
var phone = document.getElementById("phone").value;
if (phone.length == 0) {
var w = document.getElementById("phoneError").textContent;
alert(w);
return false;
}
if (phone.length != 10) {
var r = document.getElementById("phoneError").textContent;
alert(r);
return false;
}
// THIS IS NOT WORKING
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
var t = document.getElementById("phoneError").textContent;
alert(t);
return false;
}
}
Two things: First, you are mixing up AND and OR:
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
As soon as one of the conditions fails, it will return false (which is basically always). You want this if to apply, when none of the expressions matches, e.g. when all of them are false. Therefor, you have to use && instead of ||. Not a AND not b AND not c.
Second: your 3rd regex is a bit off: . means "any character", so this regex would also match "123x123y1234". You need to escape the dot with a backslash: /^\d{3}\.\d{3}\.\d{4}$/
Also, you can improve this code significantly. You have 5 conditions, which could all be handled in one (if you want to allow the input of "123.123 234", otherwise you will have to do it using 3 regex). And for just checking if a regex matches a string, you maybe should use test(), because it is just slightly faster (it won't matter in your case, but just out of principle).
You can reduce your code to:
if (/^\d{3}[\s-.]\d{3}[\s-.]\d{4}$/.test(document.getElementById("phone").value) === false) {
alert (document.getElementById("phoneError").textContent);
return false;
}

JavaScript - Regex to remove code / special characters / numbers etc

Answer #Wiktor Stribiżew suggested:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
}
Hello during the creation of an array I have a function that will not allow words with certain characters etc to be added to the array
function myValidate(word) {
// No one letter words
if (word.length === 1) {
return true;
}
if (word.indexOf('^') > -1 || word.indexOf('$') > -1) {
return true;
}
return false;
}
It seems like not the proper way of going about this and ive been looking into a regex that would handle it but have not been successful implementing it, tried numerous efforts like:
if (word.match('/[^A-Za-z]+/g') ) {
return true;
}
can some one shed some light on the proper way of handling this?
I suggest using a simpler solution:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? false : true;
}
var words = ["Fat", "Gnat", "x3-2741996", "1996", "user[50]", "definitions(edit)", "synopsis)"];
document.body.innerHTML = JSON.stringify(words.filter(x => myValidate(x)));
Where:
word.length === 1 checks for the string length
/[^A-Z]/i.test(word) checks if there is a non-ASCII-letter symbol in the string
If any of the above condition is met, the word is taken out of the array. The rest remains.
EDIT: using test instead of match
You want to use test() because it returns a bool telling you if you match the regex or not. The match(), instead, always returns the matched elements. Those may be cast to true by coercion. This is not what you want.
To sum it all up you can just use this one-liner (no if needed and no quotes either, cannot get any simpler):
return word.test(/^[a-zA-Z][a-zA-Z]+$/); // two letter words
You should whitelist characters instead of blacklisting. That's one of the principles in security. In your case, don't tell what is wrong, but tell what is right:
if (word.test('/^[a-zA-Z]+$/')) { // two letter words
return false;
}
This will return false for all words that contain ONLY [a-zA-Z] characters. I guess this is what you want.
Your regex, instead, looked for illegal characters by negating the character group with the leading ^.
Two recommendations:
Just use regex in a positive way (without negation) and it'll be a lot easier to understand.
Also, validation functions normally return true for good data and false for bad data.
It is more readable this way:
if (validate(data))
{
// that's some good data we have here!
}

Find all instances and display alert - part 2, now with regex

Thanks for your help with my earlier question:
How to find all instances and display in alert
Now I discover that I need to include some invalid character validation.
I'm trying to figure out how to include a set of regex invalid characters as part of the validation that will also show up in the same alert/textbox/whatever as the "too long/too short" validation.
So, I have a textbox which users will type or paste comma separated values such as AAAAAAA,BBBBBBB,CCCCCCCC,DDDDDDDD
And they cannot be more or less than seven characters long and they can only include certain characters.
I currently have have two separate pieces of Javascript that I'm trying to now combine:
var Invalidchars = "1234567890!##$%^&*()+=[]\\\';./{}|\":<>?";
for (var i = 0; i < document.getElementById("TextBox1").value.length; i++) {
if (Invalidchars.indexOf(document.getElementById("TextBox").value.charAt(i)) != -1){
alert
and this
var val = document.getElementById("Textbox1").value,
err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
return true;
Any help is much appreciated!
=================================================
SOLUTION
Took a while, but using Tenub's code (which didn't quite combine my two sets code, but was close enough), I finally figured out how to merge my two sets of code into one. Here's the code if anyone is ever interested in using it:
var val = document.getElementById("TextBox1").value,
err = $.grep(val.split(','), function(a) {return (a.length = (!/^[^0-9!##$%^&*()+=;.\/\{}|:<>\\?\[\]\'\"]{7}$/.test(a)));});
if (err.length){
document.getElementById("DIV1").style.display = "inline-block";
document.getElementById("TextBox2").value = err.join(',');
return callback (false);
}
document.getElementById("DIV1").style.display = "none";
return true;
The answer is as simple as it is elegant:
var val = document.getElementById("Textbox1").value;
if(!/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test(val)) {
// handle invalid value
}
This tests that the string is 7 characters in length and does not contain any character within the brackets after the "^" (also some characters are escaped with a "\").
You can test in console:
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adfFDKZ'); // returns true
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adf(DKZ'); // returns false
Try this:
/*
* This regex matches all the invalid characters. I escaped the
* special characters.
*/
var regex = /.*[0-9!##\$%\^&\*\(\)\+=\[\]\\';\./\{\}\|":\<\>\?]+.*/;
var text = document.getElementById("TextBox1").value;
/* Test for match...much faster than a for-loop under any circumstances */
if (text.matches(regex)) {
alert("Invalid characters present. Please correct the input");
return false;
}
/* split on delimiter */
var err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
Please tell me if there are any bugs in this. Also, the only real way to test for this in one step is to set up an enormously long regex. Also, with only one check, it would make it a little harder to guide the user to make the right correction. I will mention that.

Checking for uppercase/lowercase/numbers with Jquery

Either I'm being really retarded here or its just the lack of sleep but why doesn't this work? If I use the "or" operator it works for each separate test but as soon as it change it to the "and" operator it stops working.
I'm trying to test the password input of a form to see if its contains lowercase, uppercase and at least 1 number of symbol. I'm having a lot of trouble with this so help would be lovely, here is the code I have.
var upperCase= new RegExp('[^A-Z]');
var lowerCase= new RegExp('[^a-z]');
var numbers = new RegExp('[^0-9]');
if(!$(this).val().match(upperCase) && !$(this).val().match(lowerCase) && !$(this).val().match(numbers))
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
else
{
$("#passwordErrorMsg").html("OK")
}
All of your regular expressions are searching for anything except the ranges that you have provided. So, [^A-Z] looks for anything but A-Z.
You are also negating each match.
You might try modifying your regular expression definitions by removing the ^, and then reversing your logic. So,
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers))
{
$("#passwordErrorMsg").html("OK")
}
else
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
This might even be a bit more intuitive to read?
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers) && $(this).val().lenght>=6 && $(this).val()<=20)
{
$("#passwordErrorMsg").html("OK")
}
else
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}

Categories

Resources