Validate number formats in a contact form (javascript) - 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;
}

Related

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!
}

Restrict text input to number groups separate by a non-consecutive character

I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );

How to do email address validation using Javascript (without JQuery)? [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 7 years ago.
I'm trying to do an email address validation for an input text field, however, it must only submit if the entry is not null and has the # char in it
Example 1 is the one that works, however, it excludes the need for the # char
function emailvalidation() {
var x=document.forms["input"]["email"].value;
if (x==null || x=="") {
alert("Input email address, please!");
return false
}
Example 2 which does not work, but is how I imagine it would be written
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x<>null || x<>"" && x.value.match(email)) {
alert("Input email address, please!");
return true
} else {
alert("Input email address, please!");
return false
}
}
Anyone have any ideas? Thank you though, preferably without JQuery! Thanks!
Another email validation.
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
You have a couple of logical problems in your solution.
Firstly, the condition is that x is not null and x is not an empty string and x matches the pattern.
Secondly, <> is the wrong comparator for javascript; use != or !==.
Thirdly, as pointed out by putvande x is already the element's value, so x.value.match() is probably causing you issues.
function emailvalidation() {
var x = document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true;
} else {
alert("Input email address, please!");
return false;
}
}
Thank you all for this! The solution was a mixture of all of the answers! Though, here is the final solution! Needed a new reg expression and !==
Thank you all though, from a JS beginner, it is really appreciated
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true
} else {
alert("Input email address, please!");
return false
}
}
Based on your first script and requirements, one solution without regex, and one with.
Note that a text-inputfield only returns strings.
Email-addresses must have something before the #, so we check if an # appears after the first character (using indexOf we don't require a regex). Also, if we have found the # that means the string was not empty!!
If the # is at the same position as the last # and this position is smaller then the total string-length, this gives us a true or false value, which we can instantly return.
If none of the three conditions is met, then we alert our error-message. alert returns undefined (which in itself coerces to false in javascript, but) which we force to a boolean false using double not !! and return that value.
The second example follows the same logic, but uses a regex.
function emailvalidation(){ //without regex
var s=document.forms.input.email.value
, x=s.indexOf('#');
return( x>0 && x===(x=s.lastIndexOf('#')) && x<s.length-1
) || !!alert("Input email address, please!");
}
function emailvalidation(){ //with regex
return /^[^#]+#[^#]+$/.test(document.forms.input.email.value) || !!alert("Input email address, please!");
}
<form name="input">
<input name="email" type="text" />
</form>
<button onclick="alert(emailvalidation())">test</button>
Final note, it's good that you are liberal in accepting email-addresses, since trying to do a good job in regex is long and difficult, see for example this regex: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
There is simply no 100% reliable way of confirming a valid email address other than sending an email to user and and waiting for a response. See also https://softwareengineering.stackexchange.com/questions/78353/how-far-should-one-take-e-mail-address-validation
If you do try to regex 'valid email-addresses' then inform your employer that you are going to cost him business/clients/cash!!!

Efficient regex for Canadian postal code function

var regex = /[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d/;
var match = regex.exec(value);
if (match){
if ( (value.indexOf("-") !== -1 || value.indexOf(" ") !== -1 ) && value.length() == 7 ) {
return true;
} else if ( (value.indexOf("-") == -1 || value.indexOf(" ") == -1 ) && value.length() == 6 ) {
return true;
}
} else {
return false;
}
The regex looks for the pattern A0A 1B1.
true tests:
A0A 1B1
A0A-1B1
A0A1B1
A0A1B1C << problem child
so I added a check for "-" or " " and then a check for length.
Is there a regex, or more efficient method?
User kind, postal code strict, most efficient format:
/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i
Allows:
h2t-1b8
h2z 1b8
H2Z1B8
Disallows:
Z2T 1B8 (leading Z)
H2T 1O3 (contains O)
Leading Z,W or to contain D, F, I, O, Q or U
Add anchors to your pattern:
var regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
^ means "start of string" and $ means "end of string". Adding these anchors will prevent the C from slipping in to the match since your pattern will now expect a whole string to consist of 6 (sometimes 7--as a space) characters. This added bonus should now alleviate you of having to subsequently check the string length.
Also, since it appears that you want to allow hyphens, you can slip that into an optional character class that includes the space you were originally using. Be sure to leave the hyphen as either the very first or very last character; otherwise, you will need to escape it (using a leading backslash) to prevent the regex engine from interpreting it as part of a character range (e.g. A-Z).
This one handles us and ca codes.
function postalFilter (postalCode) {
if (! postalCode) {
return null;
}
postalCode = postalCode.toString().trim();
var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
var ca = new RegExp(/([ABCEGHJKLMNPRSTVXY]\d)([ABCEGHJKLMNPRSTVWXYZ]\d){2}/i);
if (us.test(postalCode.toString())) {
return postalCode;
}
if (ca.test(postalCode.toString().replace(/\W+/g, ''))) {
return postalCode;
}
return null;
}
// these 5 return null
console.log(postalFilter('1a1 a1a'));
console.log(postalFilter('F1A AiA'));
console.log(postalFilter('A12345-6789'));
console.log(postalFilter('W1a1a1')); // no "w"
console.log(postalFilter('Z1a1a1')); // ... or "z" allowed in first position!
// these return canada postal less space
console.log(postalFilter('a1a 1a1'));
console.log(postalFilter('H0H 0H0'));
// these return unaltered
console.log(postalFilter('H0H0H0'));
console.log(postalFilter('a1a1a1'));
console.log(postalFilter('12345'));
console.log(postalFilter('12345-6789'));
console.log(postalFilter('123456789'));
// strip spaces
console.log(postalFilter(' 12345 '));
You have a problem with the regex StatsCan has posted the rules for what is a valid Canadian postal code:
The postal code is a six-character code defined and maintained by
Canada Post Corporation (CPC) for the purpose of sorting and
delivering mail. The characters are arranged in the form ‘ANA NAN’,
where ‘A’ represents an alphabetic character and ‘N’ represents a
numeric character (e.g., K1A 0T6). The postal code uses 18 alphabetic
characters and 10 numeric characters. Postal codes do not include the
letters D, F, I, O, Q or U, and the first position also does not make
use of the letters W or Z.
The regex should be if you wanted it strict.
/^[ABCEGHJ-NPRSTVXY][0-9][ABCEGHJ-NPRSTV-Z] [0-9][ABCEGHJ-NPRSTV-Z][0-9]$/
Also \d means number not necessarily 0-9 there may be the one errant browser that treats it as any number in unicode space which would likely cause issues for you downstream.
from: https://trajano.net/2017/05/canadian-postal-code-validation/
This is a function that will do everything for you in one shot. Accepts AAA BBB and AAABBB with or without space.
function go_postal(){
let postal = $("#postal").val();
var regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
var pr = regex .test(postal);
if(pr === true){
//all good
} else {
// not so much
}
}
function postalFilter (postalCode, type) {
if (!postalCode) {
return null;
}
postalCode = postalCode.toString().trim();
var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
// var ca = new RegExp(/^((?!.*[DFIOQU])[A-VXY][0-9][A-Z])|(?!.*[DFIOQU])[A-VXY][0-9][A-Z]\ ?[0-9][A-Z][0-9]$/i);
var ca = new RegExp(/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i);
if(type == "us"){
if (us.test(postalCode.toString())) {
console.log(postalCode);
return postalCode;
}
}
if(type == "ca")
{
if (ca.test(postalCode.toString())) {
console.log(postalCode);
return postalCode;
}
}
return null;
}
regex = new RegExp(/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i);
if(regex.test(value))
return true;
else
return false;
This is a shorter version of the original problem, where value is any text value. Furthermore, there is no need to test for value length.

Javascript check for spaces

I have this function but I want to check for spaces only in the front and back, not in the middle before i sent back what can i do with it...
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++){
if(validChars.indexOf(val.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
return true;
}
Time for regular expressions.
function startsOrEndsWithWhitespace(str)
{
return /^\s|\s$/.test(str);
}
Tests:
> /^\s|\s$/.test('123454')
false
> /^\s|\s$/.test('123 454')
false
> /^\s|\s$/.test(' 123454')
true
> /^\s|\s$/.test(' 123454 ')
true
> /^\s|\s$/.test('123454 ')
true
if i dont wanna accept 1 1 what do i have to change
function containsWhitespace(str)
{
return /\s/.test(str);
}
Tests:
> /\s/.test('123454')
false
> /\s/.test('123 454')
true
> /\s/.test(' 123454')
true
> /\s/.test('123454 ')
true
> /\s/.test(' 123454 ')
true
> /\s/.test(' 123 454 ')
true
For a really simple solution, if you can use jQuery, use jQuery.trim() and compare the trimmed string with the original. If not equal, then there were spaces so the number is invalid.
function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
source
To trim your string you can write something like this, as it's been said before:
function trim(str){
return str.replace(/^\s+|\s+$/g), '');
}
But why bother?
Want you really want is:
function validateNumeric(str) {
return !isNaN(parseFloat(str));
}
Note your original code accepts something like "..." or "7.8..9" as being numeric, which is wrong.
Update: kennebec has called my attention to the fact that parseFloat() will ignore trailing garbage at the end of string. So I call your attention to this alternative given in an answer to question "Validate numbers in JavaScript - IsNumeric()":
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
(Original credit goes to CMS).
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
if (!/^\s*(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(val)) {
alert('Please enter a valid number');
return false;
}
return true;
}
(?:\d+(?:\.\d*)|\.\d+) breaks down as follows:
\d+ is any number of digits, e.g. 123
(\.\d*)? optionally matches a fraction, e.g. .25 and . or blank but not .1.2
\.\d+ matches a fraction without an integer part as in .5 but not 1.5.
(?:abc|def) groups things together and matches either abc or def
/^\s*(?:\d+(?:\.\d*)|\.\d+)\s*$/ means any number of spaces followed by one or more decimal digits followed by any number of spaces. So it does what your validChars loop did plus allows spaces at the start and end.

Categories

Resources