Validate email as you type - javascript

I want to validate input as I type so I use onkeyup event to do so, but if I validate an email regex "name#domain.com", as soon as user starts to type it throws an error - first character doesnt match regex...
So I wrote this:
var addValidation = function (patterns) {
var index = patterns.length; //I know I can avoid this
while (index--) {
patterns[index] = new RegExp(patterns[index]);
}
index = 0;
var current = patterns[index],
matchExact = function (patt, str) {
var match = str.match(patt);
return match !== null && str === match[0];
};
return function () {
var str = this.value;
if (!matchExact(current, str) ) {
var tmp = patterns[index + 1] ?
new RegExp(current.source + patterns[index + 1].source) :
false;
if (tmp && matchExact(tmp, str)) {
current = tmp;
index++;
}
else {
alert("Wrong");
}
}
}
};
document.getElementById("x").onkeyup = addValidation(["[a-zA-Z0-9\\.]+", "#{1}", "[a-zA-Z0-9]+", "\\.{1}", "[a-zA-Z]{1,3}"]);
It seems to work, but... it's ugly and it will alert you if you do step back (eg. "name#" and you press backspace).
I know that Dojo's validation is great, but I do not want to use Dojo. Are there any better ways to achieve that?
//EDIT: http://livedocs.dojotoolkit.org/dijit/form/ValidationTextBox this is an example, but you can define your own pattern (like email regex) and it will validate it perfectly.

Add interval before validation will start:
var t;
document.getElementById("x").onkeyup = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
//do validation
}, 1000)
}

Don't ever try to validate an email address with a regualr expression. You'll either end up allowing addresses which are not valid, or block email addresses which are perfectly valid and just annoy your visitors. It's also worth bearing in mind that the best regex so far for validating email addresses is this:
http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Related

How to: $(this) ToUpperCase

I'm no professional and after research, I wasn't able to find a solution.
I have a JavaScript source code for a SharePoint list to implement the InstantListFilter (https://archive.codeplex.com/?p=instantlistfilter) which works!
But I would like to update the source code so that the filter is NOT case sensitive. I was able to replace the the filter word (val) to uppercase (val = val.toUpperCase()). But I have no idea how to get the list-text to uppercase.
$("table.ms-listviewtable").children("tbody").each(function() {
$(this).children("tr").each(function() {
var mismatch = false;
$(this).children("td").each(function(colIndex) {
if (mismatch) return;
if (filterValues[colIndex]) {
var val = filterValues[colIndex];
// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));
val = val.toUpperCase(); //my adaption, working for the filter word
$(this).val = $(this).val().toUpperCase(); //not working for the list-text
// verifies the filter word.
if ($(this).is(":not(:contains('" + val + "'))")) {
mismatch = true;
}
}
});
if (mismatch) {
$(this).hide();
} else {
$(this).show();
}
});
});
Does anybody have a solution?
Would be happy with a short reply!
The solution you are trying will also modify the input value to upper case, i'm not sure you want that? Maybe you could assign the input value to a var and see if it contains the text with String.indexOf()
...
val = val.toUpperCase(); //my adaption, working for the filter word
var inputVal = $(this).val().toUpperCase();
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val) === -1) {
mismatch = true;
}
...
thanks for reply!!!
I got it:
var inputVal = $(this).text().toUpperCase();
//alert(inputVal);
// verifies the filter word.
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val.toUpperCase()) === -1) {
mismatch = true;
}

JS Regex url validation

I tried to validate url with or without http No matter what i did the function return false.
I checked my regex string in this site:
http://regexr.com/
And its seen as i expect.
function isUrlValid(userInput) {
var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/";
var url = new RegExp(regexQuery,"g");
if (url.test(userInput)) {
alert('Great, you entered an E-Mail-address');
return true;
}
return false;
}
I fix the problem by change the .test to .match and leave the regex as is.
I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)
The fixed function:
function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}
I believe the other answer will reject some valid url's (like domain names in uppercase or long sub-domains) and allow some invalid ones (like http://www.-example-.com or www.%#&.com). I tried to take into account a number of additional url syntax rules (without getting into internationalisation).
function isUrlValid(userInput) {
var regexQuery = "^(https?://)?(www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\.[a-z]{2,6}(/[-\\w#\\+\\.~#\\?&/=%]*)?$";
var url = new RegExp(regexQuery,"i");
return url.test(userInput);
}
var input = ["https://o.sub-domain.example.com/foo/bar?foo=bar&boo=far#a%20b",
"HTTP://EX-AMPLE.COM",
"example.c",
"example-.com"];
for (var i in input) document.write(isUrlValid(input[i]) + ": " + input[i] + "<br>");
To also allow IP addresses and port numbers, the regex is:
"^(https?://)?(((www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z‌​0-9]{0,61}[a-z0-9]\\‌​.[a-z]{2,6})|((\\d{1‌​,3}\\.){3}\\d{1,3}))‌​(:\\d{2,4})?(/[-\\w#‌​\\+\\.~#\\?&/=%]*)?$‌​"
To also allow query strings without a slash between the domain name and the question mark (which is theoretically not allowed, but works in most real-life situations), the regex is:
"^(https?://)?(((www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z‌​0-9]{0,61}[a-z0-9]\\‌​.[a‌​-z]{2,6})|((\\d‌​{1,3}\\.){3}\\d{1,3}‌​))(:\\d{2,4})?((/|\\‌​?)[-\\w#\\+\\.~#\\?&‌​/=%]*)?$"
To also make sure that every % is followed by a hex number, the regex is:
"^(https?://)?(((www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z‌​0-9]{0,61}[a-z0-9]\\‌​.[a-z]{2,6})|((\\d{1‌​,3}\\.){3}\\d{1,3}))‌​(:\\d{2,4})?((/|\\?)‌​(((%[0-9a-f]{2})|[-\‌​\w#\\+\\.~#\\?&/=])*‌​))?$"
(Note: as John Wu mentioned in a comment, there are valid single-letter domains).
Actually, this question needs a powerful regex and the following code is not very hard to understand, please see below(ES6 - TypeScript):
const isValidUrl = (url: string): boolean => {
const urlRegex = /^((http(s?)?):\/\/)?([wW]{3}\.)?[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/g;
const result = url.match(urlRegex);
return result !== null;
};
Try this code.
function CheckURL(fieldId, alertMessage) {
var url = fieldId.value;
if(url !== "")
{
if (url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g) !== null)
return true;
else {
alert(alertMessage);
fieldId.focus();
return false;
}
}
}
var website = document.getElementById('Website');
if (!CheckURL(website, "Enter a valid website address")) {
return false;
}

jQuery Validation plugin custom method using regex

I need to make a new method for jQuery Validator and don't know where to start.
I would like it check that the email entered includes: '#specificdomain.com'.
But that it is also the very last part of the input. For example #specificdomain.comChris would not do.
<script type="text/javascript">
jQuery.validator.addMethod("mustinclude", function(value, element) {
return this.optional(element) || value == ?
}, "must include #specificdomain.com at the end of the text input");
$(document).ready(function(){ .....
So far I've only come across value == value.match(), hence this is where I've got stuck.
Cheers Chris
jQuery.validator.addMethod('matchDomain', function(value, element) {
var s=value;
var split = s.split('#');
var regex = /^([a-zA-Z0-9_.+-])+$/;
var s2="#allcoles.com";
var optionalValue = this.optional(element);
if (optionalValue) {
return optionalValue;
}
if(regex.test(split[0]) && s2.equals(split[1]))
{
return true;
}
else
{
return false;
}
}, 'Please specify a #allcoles.com email');
The following worked for me:
jQuery.validator.addMethod('matchDomain', function(value, element) {
var s=value;
var split = s.split('#');
var regex = /^([a-zA-Z0-9_.+-])+$/;
**var s2="allcoles.com";** //The split array is the domain excluding the #
**var optionalValue = this.optional(element);** //This is how other methods in alternativeMethods.js Validator handle this.
**//Debugging - This is useful to see visually what is happening
//alert(split[0]); // Shows the inputted username i.e chris or smokey
//alert(split[1]); // Shows the inputted domain
//alert(regex.test(split[0])); //Shows unfilled inputs problem or bad characters, true if good, false if bad
//alert(s2 == split[1]);** // Shows if the inputted domain matches variable s2, if it does we get a true
if (optionalValue) {
return optionalValue;
}
**if(regex.test(split[0]) && (s2 == split[1]))** // has to be == not equals
{
return true;
}
else
{
return false;
}
}, 'Please specify a #allcoles.com email');
var s="abc#specificdomain.com"; OR var s=value;
var split = s.split('#');
var regex = /^([a-zA-Z0-9_.+-])/;
var s2="#specificdomain.com";
if(regex.test(split[0]) && s2 == split[1])
return true;
else
return false;

Javascript isEmailValid

Using JSLint I can't get my isEmailValid working, what is wrong with the code? I get different error messages like local was not defined before it was used or # invalid character or ^ is not enclosed but for the email it could have the symbol "^"?
function isEmailValid(email) {
"use strict";
var e = (email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
Validate email addresses client-side with this regular expression:
/.#./
And then do the real validation server-side by sending an email to that address.
Working email addresses can and do exist that do not conform to any spec. There's no sense restricting users because their valid email address looks wrong, while at the same time allowing users to enter email addresses that look right, but are fake (eg, iwontgiveyoumyrealemailaddress#noreply.com looks real to a computer, but probably isn't).
Required reading
I would suggest using regex:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
See also: Validate email address in JavaScript?
You're getting the error about local because you're not actually declaring it as a local variable within the function.
var statements don't contain or use parenthesis. So, using them anyways as:
var e = (email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
Is equivalent to:
local = /[^\w.!#$%&*+-\/=?^_{|}~]/;
domain = /[^\w.-]/;
var e = (email.split("#"), local, domain);
e will then be set to the result of the parenthesis being evaluated, which simply contain operands for comma operators. So, the last line is equivalent to:
email.split("#");
local;
var e = domain;
And, as that doesn't seem to be what you wanted, you probably don't want the parenthesis:
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/;

What is a good regular expression to match a URL? [duplicate]

This question already has answers here:
What is the best regular expression to check if a string is a valid URL?
(62 answers)
Closed 8 years ago.
Currently I have an input box which will detect the URL and parse the data.
So right now, I am using:
var urlR = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)
(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url= content.match(urlR);
The problem is, when I enter a URL like www.google.com, its not working. when I entered http://www.google.com, it is working.
I am not very fluent in regular expressions. Can anyone help me?
Regex if you want to ensure URL starts with HTTP/HTTPS:
https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)
If you do not require HTTP protocol:
[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)
To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.
Example JavaScript implementation:
var expression = /[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = 'www.google.com';
if (t.match(regex)) {
alert("Successful match");
} else {
alert("No match");
}
(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})
Will match the following cases
http://www.foufos.gr
https://www.foufos.gr
http://foufos.gr
http://www.foufos.gr/kino
http://werer.gr
www.foufos.gr
www.mp3.com
www.t.co
http://t.co
http://www.t.co
https://www.t.co
www.aa.com
http://aa.com
http://www.aa.com
https://www.aa.com
Will NOT match the following
www.foufos
www.foufos-.gr
www.-foufos.gr
foufos.gr
http://www.foufos
http://foufos
www.mp3#.com
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;
var regex = new RegExp(expression);
var check = [
'http://www.foufos.gr',
'https://www.foufos.gr',
'http://foufos.gr',
'http://www.foufos.gr/kino',
'http://werer.gr',
'www.foufos.gr',
'www.mp3.com',
'www.t.co',
'http://t.co',
'http://www.t.co',
'https://www.t.co',
'www.aa.com',
'http://aa.com',
'http://www.aa.com',
'https://www.aa.com',
'www.foufos',
'www.foufos-.gr',
'www.-foufos.gr',
'foufos.gr',
'http://www.foufos',
'http://foufos',
'www.mp3#.com'
];
check.forEach(function(entry) {
if (entry.match(regex)) {
$("#output").append( "<div >Success: " + entry + "</div>" );
} else {
$("#output").append( "<div>Fail: " + entry + "</div>" );
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
Check it in rubular - NEW version
Check it in rubular - old version
These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.
function isURL(str) {
var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?#)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
var url = new RegExp(urlRegex, 'i');
return str.length < 2083 && url.test(str);
}
Test:
function isURL(str) {
var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?#)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
var url = new RegExp(urlRegex, 'i');
return str.length < 2083 && url.test(str);
}
var check = [
'http://www.foufos.gr',
'https://www.foufos.gr',
'http://foufos.gr',
'http://www.foufos.gr/kino',
'http://werer.gr',
'www.foufos.gr',
'www.mp3.com',
'www.t.co',
'http://t.co',
'http://www.t.co',
'https://www.t.co',
'www.aa.com',
'http://aa.com',
'http://www.aa.com',
'https://www.aa.com',
'www.foufos',
'www.foufos-.gr',
'www.-foufos.gr',
'foufos.gr',
'http://www.foufos',
'http://foufos',
'www.mp3#.com'
];
for (let index = 0; index < check.length; index++) {
var url=check[index]
if (isURL(check[index]))
console.log(`${url} ✔`);
else{
console.log(`${url} ❌`);
}
}
Result
Another possible solution, above solution failed for me in parsing query string params.
var regex = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.#:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if(regex.test("http://google.com")){
alert("Successful match");
}else{
alert("No match");
}
In this solution please feel free to modify [-0-9A-Za-z\.#:%_\+~#=, to match the domain/sub domain name. In this solution query string parameters are also taken care.
If you are not using RegEx, then from the expression replace \\ by \.
Hope this helps.
Test:-
function IsUrl(url){
var regex = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.#:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if(regex.test(url)){
console.log(`${url} ✔`);
}else{
console.log(`${url} ❌`);
}}
var check = [
'http://www.foufos.gr',
'https://www.foufos.gr',
'http://foufos.gr',
'http://www.foufos.gr/kino',
'http://werer.gr',
'www.foufos.gr',
'www.mp3.com',
'www.t.co',
'http://t.co',
'http://www.t.co',
'https://www.t.co',
'www.aa.com',
'http://aa.com',
'http://www.aa.com',
'https://www.aa.com',
'www.foufos',
'www.foufos-.gr',
'www.-foufos.gr',
'foufos.gr',
'http://www.foufos',
'http://foufos',
'www.mp3#.com'
];
for (let index = 0; index < check.length; index++) {
IsUrl(check[index])
}
Result
I was trying to put together some JavaScript to validate a domain name (ex. google.com) and if it validates enable a submit button. I thought that I would share my code for those who are looking to accomplish something similar. It expects a domain without any http:// or www. value. The script uses a stripped down regular expression from above for domain matching, which isn't strict about fake TLD.
http://jsfiddle.net/nMVDS/1/
$(function () {
$('#whitelist_add').keyup(function () {
if ($(this).val() == '') { //Check to see if there is any text entered
//If there is no text within the input, disable the button
$('.whitelistCheck').attr('disabled', 'disabled');
} else {
// Domain name regular expression
var regex = new RegExp("^([0-9A-Za-z-\\.#:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if (regex.test($(this).val())) {
// Domain looks OK
//alert("Successful match");
$('.whitelistCheck').removeAttr('disabled');
} else {
// Domain is NOT OK
//alert("No match");
$('.whitelistCheck').attr('disabled', 'disabled');
}
}
});
});
HTML FORM:
<form action="domain_management.php" method="get">
<input type="text" name="whitelist_add" id="whitelist_add" placeholder="domain.com">
<button type="submit" class="btn btn-success whitelistCheck" disabled='disabled'>Add to Whitelist</button>
</form>

Categories