I have 2 input fields on my form: email and website
How do I use JQuery to validate the email address domain must matched with the website domain?
For example: if website is http://example.com or with www or without http:// or without http://www.
Then the email address field must be user#example.com
Here is my form https://jsfiddle.net/zm7e8r7p/
$(document).ready(function(){
$( "#target" ).submit(function( event ) {
var val = $("#website").val();
var myString = val.substr(val.indexOf("http://") + 7);
var emailString = $("#email").val();
var myEmail = emailString.substr(emailString.indexOf("#")+1);
if (myString == myEmail){
$( "span" ).text( "Validated..." ).show();
event.preventDefault();
}else{
$( "span" ).text( "Not valid!" ).show();
event.preventDefault();
}
});
});
You can use URL regex by Crockford
Getting only last two parts of domain name is optional, you can use it if you want to convert ww2.mobile.gmail.com into gmail.com. This logic will affect domain names like .co.in as #samanime points out
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = 'www.mobile.ora.co.in:80/goodparts?q#fragment';
var result = parse_url.exec(url);
var hostName = result[3];
console.log("host name: ", hostName);
lastTwo = hostName.split('.');
lastTwo = lastTwo.length>2?lastTwo.slice(Math.max(lastTwo.length - 2, 1)) : lastTwo;
onlyMainDomain = lastTwo.join('.');
console.log('only main domain:', onlyMainDomain);
var email = "someone#ora.co.in";
var emailDomain = email.split('#')[1];
console.log('email domain:', emailDomain);
console.log("valid?" , emailDomain === onlyMainDomain);
//check if email domain is a child of hostName
emailDomainRev = emailDomain.split('.').reverse();
hostNameRev = hostName.split('.').reverse();
var emailDomainIsChildOfHostName = true;
if(emailDomainRev.length > hostNameRev.length){
emailDomainIsChildOfHostName = false;
}
else{
emailDomainIsChildOfHostName = emailDomainRev.reduce(function(acc, item, index){
return acc && (item === hostNameRev[index]);
},true);
}
console.log("email domain is a child of host name:", emailDomainIsChildOfHostName);
Here is a simple JavaScript process to validate email with your domain name.
function ValidateEmail(email) {
var re = /\S+#\S+\.\S+/; /*Regular expression for valid email*/
return re.test(email); /*Return `true` if valid, Otherwise return `false`*/
}
var domain = 'www.example#example.com';
var email ='emaxple#example.com';
if(ValidateEmail(email)){
email = email.split('#'); /* Split email after `#` Sign*/
email = email[1] /*After split, `email[0]=emaxple, email[1]=emaxple.com`*/
domain = domain.split('').reverse().join(''); /*Now `domain = moc.elpmaxe#elpmaxe.www`*/
email = email.split('').reverse().join(''); /*Now `email = moc.elpmaxe*/
email = email + '#'; /*Now `email = moc.elpmaxe#`*/
if(domain.indexOf(email)==0){ /*If only return `0` then valid, Otherwise Invalid*/
/*Valid with your domain*/
}else{
/*Doesn't match with your domain*/
}
}else{
/*Invalid Email*/
}
I've added the regular expression Wiktor suggested with a minor change to accept url without protocol.
Your code would look like this:
$(document).ready(function(){
$("#target").submit(function(event) {
var website = $("#website").val();
var websiteDomain = website.replace(/^(https?:\/\/)?(?:www\.)?/, "");
var email = $("#email").val();
var emailDomain = email.substr(email.indexOf("#")+1);
$("span").text(websiteDomain === emailDomain ? "Valid!" : "Not valid!" ).show()
event.preventDefault();
});
});
There is a tricky part to your question. Technically, you can have a domain with any number of parts. For example: this.is.a.valid.domain.com
With the new custom top-level domains, it can get even trickier, since they make it possible to have all kinds of crazy combinations and lengths. For example: this.is.also.a.valid.name.on.the.top.level.cake
Looks nothing like a domain, but if you owned the top-level domain cake, you could make it happen.
So, you can't really trim off the sub-domain and ensure that www.example.com results in an email #example.com. However, you can tell if it's on at least #www.example.com, #example.com or #com, which could all be valid. (In reality, you couldn't have one on any of the controlled top-level domains, but it's probably good to allow it for those rare cases.)
This is why most websites require you to click a link in an email sent to you to validate your URL.
Using the above criteria I just described, you can do it with this:
var website = "http://www.example.com"; // website from form
var email = "me#example.com"; // email from form
var emailDomain = email.split('#')[1];
var websiteDomain = website.match(/^(?:https?:\/\/)?([^\/]+)/)[1];
var isValidEmail = (websiteDomain || '').lastIndexOf(emailDomain) === (websiteDomain || '').length - (emailDomain || '').length;
isValidEmail will then contain true if it is a valid match, or false if it isn't.
I've added checks for if something fails above so it won't throw an error if one of the above parts are bad. If you're giving an invalid website, websiteDomain will be undefined. Likewise for a completely invalid email, emailDomain will be `undefined.
I update your code. I give you the link here
https://jsfiddle.net/zm7e8r7p/5/
$(document).ready(function(){
$( "#target" ).submit(function(event) {
event.preventDefault();
var emailString = $("#email").val();
//cut rule by #
var afterAt = emailString.split('#');
var val = $("#website").val();
var myString = val.substr(-(afterAt[1].length));
console.log(afterAt[1].length);
if (myString == afterAt[1]){
console.log('works');return
}else{
console.log('not');return
};
});
});
Related
I want to validate this text field email which contains Multiple emails; all separated by semi colons but this isn't working. It should break when msn.com have been entered along with other emails.
var isMsn = ["msn.com"];
function myFunction() {
var str = email.value;
//var isMsn = str.includes("msn.com");
var res = str.split(";");
var isValid = false;
//alert(res.length);
for (var i = 0; i < res.length; i++){
//alert(res[i]);
var x = res[i];
//check to see if this is an valid emAIL then
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(x.match(mailformat)){
alert("valid email address!");
//IF isMsn = TRUE then check to see if is contains msn.com
if (x.contains(isMsn) ){
alert("it is MSN");
//res[+1];
isValid = true;
}
else {
alert('no MSN');
if (res.includes(isMsn)){
//alert('Cannot mix MSN emails with other');
//isValid = false;
//res[-1];
break;
}
//else{
//alert('it is other');
//isValid = true;
//}
}
}
else{
alert("You have entered an invalid email address!");
isValid = false;
}
}
}
I want it to loop through and all the emails must either match a msn.com or other NOT Both. for example, user#msn.com;user1#msn.com or user#hotmail.com;user1#hotmail.com but NOT user#msn.com;user1#hotmail.com
Not sure if .includes is the best option or not!
1) You should use includes instead of contains;
2) The includes or contains method accepts a string, not an array, so it should be res.includes(isMsn[0]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
And if you want to validate by multiple domains - you should not name it isMsn, but prohibitedDomains and then to Array.some (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) over this array.
prohibitedDomains.some((domain) => res.includes(domain))
(I am very new to JavaScript and am writing this to try and get used to using it a bit more - which is why I'm using an object to store usernames and passwords. I'm learning this as part of an apprenticeship but this is during my own time to further my knowledge on JS)
I have tried writing a small piece of code that should ask the user to enter a username, which will be cross-checked against the property names in the object "userNames". The user is then asked to enter a password for this user which is then checked against the password set as the value of the corresponding property with the right username.
I feel as though part of the problem is to do with me trying to use the variable "enteredPassword" (set to the user's input for the password as a method) of "userNames".
If the username or password are incorrect after 3 attempts then I'd like the window to close.
my text editor is saying that the If statement is missing a branch and I'm not sure if this is affecting whether this works or not.
var userNames = {Tom:"PassW0rd", Bill:"Apples40C0lander", Ryan:"M1911p4ck4ge"};
var Greeting = "Insert Username:";
var i = 0;
while (i < 3)
{
var enteredUserName = prompt(Greeting);
var enteredPassword = prompt("enter password for " + enteredUserName);
if ((userNames.hasOwnProperty(enteredUserName)) && (userNames.enteredUserName==enteredPassword)) {
alert("Welcome");
break;
} else {
alert("incorrect Username or Password");
alert("");
window.open('', '_self', ''); window.close();
window.open('', '_self', ''); window.close();
i++
}}
A simple change is enough here :
userNames[enteredUserName].
In JavaScript, Object can also accessed like array.
If you use userNames.enteredUserName , then it will check {enteredUserName:somevalue} (ie, enteredUserName will be considered as a String. but if you use it as userNames[enteredUserName] , then enteredUserName will be considered as variable and index to the Object.
Try below snippet.
var userNames = {Tom:"PassW0rd", Bill:"Apples40C0lander", Ryan:"M1911p4ck4ge"};
var Greeting = "Insert Username:";
var i = 0;
while (i < 3)
{
var enteredUserName = prompt(Greeting);
var enteredPassword = prompt("enter password for " + enteredUserName);
if ((userNames.hasOwnProperty(enteredUserName)) && (userNames[enteredUserName]==enteredPassword)) {
alert("Welcome");
break;
} else {
alert("incorrect Username or Password");
alert("");
window.open('', '_self', ''); window.close();
window.open('', '_self', ''); window.close();
i++
}}
I have a form where I would like the user to input a complete URL that leads directly to a PDF (not a page that contains a pdf).
Currently I am testing (and adding if necessary) for http/https link this:
var str = textfield.value;
//test for http/https and add it if not there
var httpsInc = str.indexOf('https://') !== -1;
var httpInc = str.indexOf('http://') !== -1;
if ((httpsInc == false) & (httpInc == false)) {
textfield.value = "http://" + str;
var str = textfield.value;
}
and then testing that it is a valid URL (based on another post on here):
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
testresults=1;
} else {
testresults=0;
}
return (testresults);
I was then going to add in the test for .pdf [something like str.indexOf('.pdf') !== -1] but I figured there must be a better way to do this. The RegExp above could likely do all of this testing for me I assume (test that .pdf is at the end etc), but I am unsure how to modify it. Is it better to modify it or just check that the last 4 characters of my string are ".pdf"?
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.-]/;
In my application I am using jquery validation for forms.
There are two other fileds to enter the twitter page url and facebook page url.
How can I validate these url using jquery?
Examples:
http://twitter.com/anypage
http://twitter.com/#!/anypage
http://facebook.com/anypage
None of the above solutions/regular expressions are flexible enough.
Check my code in jsFiddle.
var str1 = 'http://twitter.com/anypage'; //True
var str2 = 'http://twitter.com/#!/anypage'; //True
var str3 = 'http://facebook2.com/anypage'; //False
var str4 = 'http://www.facebook.com/anypage'; //True http & www
var str5 = 'http://facebook.com/anypage'; //True http
var str6 = 'https://facebook.com/anypage'; //True https
var str7 = 'https://www.facebook.com/anypage'; //True https & www
var str8 = 'facebook.com/anypage'; //True no protocol
var str9 = 'www.facebook.com/anypage'; //True no protocol & www
function validate_url(url)
{
if (/^(https?:\/\/)?((w{3}\.)?)twitter\.com\/(#!\/)?[a-z0-9_]+$/i.test(url))
return 'twitter';
if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
return 'facebook';
return 'unknown';
}
alert('This link is ' + validate_url(str2));
I think this may help you
function validFBurl(enteredURL) {
var FBurl = /^(http|https)\:\/\/www.facebook.com\/.*/i;
if(!enteredURL.match(FBurl)) {
alert("This is not a Facebook URL");
}
else {
alert("This IS a Facebook URL");
}
}
For Twitter just add new var for Twitter URL
var TWurl = /^(http|https)\:\/\/(www.|)twitter.com\/.*/i;
Validate:
http://twitter.com/username > TRUE
https://twitter.com/username > TRUE
http://www.twitter.com/username > TRUE
https://www.twitter.com/username > TRUE
Source:
http://www.webdeveloper.com/forum/showthread.php?t=247621
Like this?
var str1 = 'http://twitter.com/anypage';
var str2 = 'http://twitter.com/#!/anypage';
var str3 = 'http://facebook.com/anypage';
if (/https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/i.test(str1))
alert('Str1 has passed first regexp');
if (/https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/i.test(str2))
alert('Str2 has passed first regexp');
if (/https?:\/\/facebook\.com\/[a-z0-9_]+$/i.test(str3))
alert('Str3 has passed second regexp');
Or a validation function http://jsfiddle.net/36Wct/2/
var str1 = 'http://twitter.com/anypage';
var str2 = 'http://twitter.com/#!/anypage';
var str3 = 'http://facebook.com/anypage';
var str4 = 'http://facebook2.com/anypage';
function validate_url(url)
{
if (/https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/i.test(url))
return 'twitter';
if (/https?:\/\/facebook\.com\/[a-z0-9_]+$/i.test(url))
return 'facebook';
return 'unknown';
}
alert('This link is ' + validate_url(str4));
Use url() method from the jQuery Validation plugin. It checks if the entered url is valid. You can still customize it upon your requirement (which is to check if the page belongs to twitter or FB).
Source: http://docs.jquery.com/Plugins/Validation