Check if email address is Subdomain - javascript

I am trying to check if the domain belonging to an email address is a subdomain or not.
It must work with:
test#domain.com
test#domain.co.uk
test#subdomain.domain.com
test#subdomain.domain.co.uk
test#subdomain.domain.com.au
etc
So I don't think splitting the domain by . and checking how many parts is going to work.
It must be really fast as it will be processing a large array.
I have tried with the follow code:
var isSubdomain = function(email){
var pattern = new RegExp("/^\w+(?:\.\w+)*#\w+(?:\.\w+)+$/");
return pattern.test(email);
};
But this is always returning false.

To do this properly what we need to do is work out what are TLD (Top Level Domains). I found a list of these from here -> https://github.com/mikewesthad/tld-data
What I then did is convert the data and place into a Set, you could use an object literal if ES6 can't be used.
I then work backwards from the url, if it's a TLD and then go back another. Once I don't hit a TLD I'm then on the Domain, and the one's before that are then the subdomain.
Below I've made a simple function called urlInfo, with this you can use to extract the subdomain, domain, and the TLD's.
Because I've used a Set, this should run pretty fast too. If you don't want the extra info you could maybe simplify the function to squeeze a bit more speed.
const tlddata=
"aaa:aarp:abarth:abb:abbott:abbvie:abc:able:abogado:abudhabi:ac:academy:accenture"+
":accountant:accountants:aco:active:actor:ad:adac:ads:adult:ae:aeg:aero:aetna:af:"+
"afamilycompany:afl:africa:ag:agakhan:agency:ai:aig:aigo:airbus:airforce:airtel:a"+
"kdn:al:alfaromeo:alibaba:alipay:allfinanz:allstate:ally:alsace:alstom:am:america"+
"nexpress:americanfamily:amex:amfam:amica:amsterdam:an:analytics:android:anquan:a"+
"nz:ao:aol:apartments:app:apple:aq:aquarelle:ar:arab:aramco:archi:army:arpa:art:a"+
"rte:as:asda:asia:associates:at:athleta:attorney:au:auction:audi:audible:audio:au"+
"spost:author:auto:autos:avianca:aw:aws:ax:axa:az:azure:ba:baby:baidu:banamex:ban"+
"anarepublic:band:bank:bar:barcelona:barclaycard:barclays:barefoot:bargains:baseb"+
"all:basketball:bauhaus:bayern:bb:bbc:bbt:bbva:bcg:bcn:bd:be:beats:beauty:beer:be"+
"ntley:berlin:best:bestbuy:bet:bf:bg:bh:bharti:bi:bible:bid:bike:bing:bingo:bio:b"+
"iz:bj:bl:black:blackfriday:blanco:blockbuster:blog:bloomberg:blue:bm:bms:bmw:bn:"+
"bnl:bnpparibas:bo:boats:boehringer:bofa:bom:bond:boo:book:booking:boots:bosch:bo"+
"stik:boston:bot:boutique:box:bq:br:bradesco:bridgestone:broadway:broker:brother:"+
"brussels:bs:bt:budapest:bugatti:build:builders:business:buy:buzz:bv:bw:by:bz:bzh"+
":ca:cab:cafe:cal:call:calvinklein:cam:camera:camp:cancerresearch:canon:capetown:"+
"capital:capitalone:car:caravan:cards:care:career:careers:cars:cartier:casa:case:"+
"caseih:cash:casino:cat:catering:catholic:cba:cbn:cbre:cbs:cc:cd:ceb:center:ceo:c"+
"ern:cf:cfa:cfd:cg:ch:chanel:channel:chase:chat:cheap:chintai:chloe:christmas:chr"+
"ome:chrysler:church:ci:cipriani:circle:cisco:citadel:citi:citic:city:cityeats:ck"+
":cl:claims:cleaning:click:clinic:clinique:clothing:cloud:club:clubmed:cm:cn:co:c"+
"oach:codes:coffee:college:cologne:com:comcast:commbank:community:company:compare"+
":computer:comsec:condos:construction:consulting:contact:contractors:cooking:cook"+
"ingchannel:cool:coop:corsica:country:coupon:coupons:courses:cr:credit:creditcard"+
":creditunion:cricket:crown:crs:cruise:cruises:csc:cu:cuisinella:cv:cw:cx:cy:cymr"+
"u:cyou:cz:dabur:dad:dance:data:date:dating:datsun:day:dclk:dds:de:deal:dealer:de"+
"als:degree:delivery:dell:deloitte:delta:democrat:dental:dentist:desi:design:dev:"+
"dhl:diamonds:diet:digital:direct:directory:discount:discover:dish:diy:dj:dk:dm:d"+
"np:do:docs:doctor:dodge:dog:doha:domains:doosan:dot:download:drive:dtv:dubai:duc"+
"k:dunlop:duns:dupont:durban:dvag:dvr:dz:earth:eat:ec:eco:edeka:edu:education:ee:"+
"eg:eh:email:emerck:energy:engineer:engineering:enterprises:epost:epson:equipment"+
":er:ericsson:erni:es:esq:estate:esurance:et:etisalat:eu:eurovision:eus:events:ev"+
"erbank:exchange:expert:exposed:express:extraspace:fage:fail:fairwinds:faith:fami"+
"ly:fan:fans:farm:farmers:fashion:fast:fedex:feedback:ferrari:ferrero:fi:fiat:fid"+
"elity:fido:film:final:finance:financial:fire:firestone:firmdale:fish:fishing:fit"+
":fitness:fj:fk:flickr:flights:flir:florist:flowers:flsmidth:fly:fm:fo:foo:food:f"+
"oodnetwork:football:ford:forex:forsale:forum:foundation:fox:fr:free:fresenius:fr"+
"l:frogans:frontdoor:frontier:ftr:fujitsu:fujixerox:fun:fund:furniture:futbol:fyi"+
":ga:gal:gallery:gallo:gallup:game:games:gap:garden:gb:gbiz:gd:gdn:ge:gea:gent:ge"+
"nting:george:gf:gg:ggee:gh:gi:gift:gifts:gives:giving:gl:glade:glass:gle:global:"+
"globo:gm:gmail:gmbh:gmo:gmx:gn:godaddy:gold:goldpoint:golf:goo:goodhands:goodyea"+
"r:goog:google:gop:got:gov:gp:gq:gr:grainger:graphics:gratis:green:gripe:grocery:"+
"group:gs:gt:gu:guardian:gucci:guge:guide:guitars:guru:gw:gy:hair:hamburg:hangout"+
":haus:hbo:hdfc:hdfcbank:health:healthcare:help:helsinki:here:hermes:hgtv:hiphop:"+
"hisamitsu:hitachi:hiv:hk:hkt:hm:hn:hockey:holdings:holiday:homedepot:homegoods:h"+
"omes:homesense:honda:honeywell:horse:hospital:host:hosting:hot:hoteles:hotels:ho"+
"tmail:house:how:hr:hsbc:ht:htc:hu:hughes:hyatt:hyundai:ibm:icbc:ice:icu:id:ie:ie"+
"ee:ifm:iinet:ikano:il:im:imamat:imdb:immo:immobilien:in:industries:infiniti:info"+
":ing:ink:institute:insurance:insure:int:intel:international:intuit:investments:i"+
"o:ipiranga:iq:ir:irish:is:iselect:ismaili:ist:istanbul:it:itau:itv:iveco:iwc:jag"+
"uar:java:jcb:jcp:je:jeep:jetzt:jewelry:jio:jlc:jll:jm:jmp:jnj:jo:jobs:joburg:jot"+
":joy:jp:jpmorgan:jprs:juegos:juniper:kaufen:kddi:ke:kerryhotels:kerrylogistics:k"+
"erryproperties:kfh:kg:kh:ki:kia:kim:kinder:kindle:kitchen:kiwi:km:kn:koeln:komat"+
"su:kosher:kp:kpmg:kpn:kr:krd:kred:kuokgroup:kw:ky:kyoto:kz:la:lacaixa:ladbrokes:"+
"lamborghini:lamer:lancaster:lancia:lancome:land:landrover:lanxess:lasalle:lat:la"+
"tino:latrobe:law:lawyer:lb:lc:lds:lease:leclerc:lefrak:legal:lego:lexus:lgbt:li:"+
"liaison:lidl:life:lifeinsurance:lifestyle:lighting:like:lilly:limited:limo:linco"+
"ln:linde:link:lipsy:live:living:lixil:lk:loan:loans:locker:locus:loft:lol:london"+
":lotte:lotto:love:lpl:lplfinancial:lr:ls:lt:ltd:ltda:lu:lundbeck:lupin:luxe:luxu"+
"ry:lv:ly:ma:macys:madrid:maif:maison:makeup:man:management:mango:map:market:mark"+
"eting:markets:marriott:marshalls:maserati:mattel:mba:mc:mcd:mcdonalds:mckinsey:m"+
"d:me:med:media:meet:melbourne:meme:memorial:men:menu:meo:merckmsd:metlife:mf:mg:"+
"mh:miami:microsoft:mil:mini:mint:mit:mitsubishi:mk:ml:mlb:mls:mm:mma:mn:mo:mobi:"+
"mobile:mobily:moda:moe:moi:mom:monash:money:monster:montblanc:mopar:mormon:mortg"+
"age:moscow:moto:motorcycles:mov:movie:movistar:mp:mq:mr:ms:msd:mt:mtn:mtpc:mtr:m"+
"u:museum:mutual:mutuelle:mv:mw:mx:my:mz:na:nab:nadex:nagoya:name:nationwide:natu"+
"ra:navy:nba:nc:ne:nec:net:netbank:netflix:network:neustar:new:newholland:news:ne"+
"xt:nextdirect:nexus:nf:nfl:ng:ngo:nhk:ni:nico:nike:nikon:ninja:nissan:nissay:nl:"+
"no:nokia:northwesternmutual:norton:now:nowruz:nowtv:np:nr:nra:nrw:ntt:nu:nyc:nz:"+
"obi:observer:off:office:okinawa:olayan:olayangroup:oldnavy:ollo:om:omega:one:ong"+
":onl:online:onyourside:ooo:open:oracle:orange:org:organic:orientexpress:origins:"+
"osaka:otsuka:ott:ovh:pa:page:pamperedchef:panasonic:panerai:paris:pars:partners:"+
"parts:party:passagens:pay:pccw:pe:pet:pf:pfizer:pg:ph:pharmacy:phd:philips:phone"+
":photo:photography:photos:physio:piaget:pics:pictet:pictures:pid:pin:ping:pink:p"+
"ioneer:pizza:pk:pl:place:play:playstation:plumbing:plus:pm:pn:pnc:pohl:poker:pol"+
"itie:porn:post:pr:pramerica:praxi:press:prime:pro:prod:productions:prof:progress"+
"ive:promo:properties:property:protection:pru:prudential:ps:pt:pub:pw:pwc:py:qa:q"+
"pon:quebec:quest:qvc:racing:radio:raid:re:read:realestate:realtor:realty:recipes"+
":red:redstone:redumbrella:rehab:reise:reisen:reit:reliance:ren:rent:rentals:repa"+
"ir:report:republican:rest:restaurant:review:reviews:rexroth:rich:richardli:ricoh"+
":rightathome:ril:rio:rip:rmit:ro:rocher:rocks:rodeo:rogers:room:rs:rsvp:ru:rugby"+
":ruhr:run:rw:rwe:ryukyu:sa:saarland:safe:safety:sakura:sale:salon:samsclub:samsu"+
"ng:sandvik:sandvikcoromant:sanofi:sap:sapo:sarl:sas:save:saxo:sb:sbi:sbs:sc:sca:"+
"scb:schaeffler:schmidt:scholarships:school:schule:schwarz:science:scjohnson:scor"+
":scot:sd:se:search:seat:secure:security:seek:select:sener:services:ses:seven:sew"+
":sex:sexy:sfr:sg:sh:shangrila:sharp:shaw:shell:shia:shiksha:shoes:shop:shopping:"+
"shouji:show:showtime:shriram:si:silk:sina:singles:site:sj:sk:ski:skin:sky:skype:"+
"sl:sling:sm:smart:smile:sn:sncf:so:soccer:social:softbank:software:sohu:solar:so"+
"lutions:song:sony:soy:space:spiegel:spot:spreadbetting:sr:srl:srt:ss:st:stada:st"+
"aples:star:starhub:statebank:statefarm:statoil:stc:stcgroup:stockholm:storage:st"+
"ore:stream:studio:study:style:su:sucks:supplies:supply:support:surf:surgery:suzu"+
"ki:sv:swatch:swiftcover:swiss:sx:sy:sydney:symantec:systems:sz:tab:taipei:talk:t"+
"aobao:target:tatamotors:tatar:tattoo:tax:taxi:tc:tci:td:tdk:team:tech:technology"+
":tel:telecity:telefonica:temasek:tennis:teva:tf:tg:th:thd:theater:theatre:tiaa:t"+
"ickets:tienda:tiffany:tips:tires:tirol:tj:tjmaxx:tjx:tk:tkmaxx:tl:tm:tmall:tn:to"+
":today:tokyo:tools:top:toray:toshiba:total:tours:town:toyota:toys:tp:tr:trade:tr"+
"ading:training:travel:travelchannel:travelers:travelersinsurance:trust:trv:tt:tu"+
"be:tui:tunes:tushu:tv:tvs:tw:tz:ua:ubank:ubs:uconnect:ug:uk:um:unicom:university"+
":uno:uol:ups:us:uy:uz:va:vacations:vana:vanguard:vc:ve:vegas:ventures:verisign:v"+
"ersicherung:vet:vg:vi:viajes:video:vig:viking:villas:vin:vip:virgin:visa:vision:"+
"vista:vistaprint:viva:vivo:vlaanderen:vn:vodka:volkswagen:volvo:vote:voting:voto"+
":voyage:vu:vuelos:wales:walmart:walter:wang:wanggou:warman:watch:watches:weather"+
":weatherchannel:webcam:weber:website:wed:wedding:weibo:weir:wf:whoswho:wien:wiki"+
":williamhill:win:windows:wine:winners:wme:wolterskluwer:woodside:work:works:worl"+
"d:wow:ws:wtc:wtf:xbox:xerox:xfinity:xihuan:xin:测试:कॉम:परीक्षा:セール:佛山:ಭಾರತ:慈善:集团:"+
"在线:한국:ଭାରତ:大众汽车:点看:คอม:ভাৰত:ভারত:八卦:.موقع‎:বাংলা:公益:公司:香格里拉:网站:移动:我爱你:москва:исп"+
"ытание:қаз:католик:онлайн:сайт:联通:срб:бг:бел:.קום‎:时尚:微博:테스트:淡马锡:ファッション:орг:नेट:"+
"ストア:삼성:சிங்கப்பூர்:商标:商店:商城:дети:мкд:.טעסט‎:ею:ポイント:新闻:工行:家電:.كوم‎:中文网:中信:中国:中國:"+
"娱乐:谷歌:భారత్:ලංකා:電訊盈科:购物:測試:クラウド:ભારત:通販:भारतम्:भारत:भारोत:.آزمایشی‎:பரிட்சை:网店:"+
"संगठन:餐厅:网络:ком:укр:香港:诺基亚:食品:δοκιμή:飞利浦:.إختبار‎:台湾:台灣:手表:手机:мон:.الجزائر‎:.عما"+
"ن‎:.ارامكو‎:.ایران‎:.العليان‎:.اتصالات‎:.امارات‎:.بازار‎:.پاکستان‎:.الاردن‎:.موب"+
"ايلي‎:.بارت‎:.بھارت‎:.المغرب‎:.ابوظبي‎:.السعودية‎:.ڀارت‎:.كاثوليك‎:.سودان‎:.همرا"+
"ه‎:.عراق‎:.مليسيا‎:澳門:닷컴:政府:.شبكة‎:.بيتك‎:.عرب‎:გე:机构:组织机构:健康:ไทย:.سورية‎:рус:рф"+
":珠宝:.تونس‎:大拿:みんな:グーグル:ελ:世界:書籍:ഭാരതം:ਭਾਰਤ:网址:닷넷:コム:天主教:游戏:vermögensberater:verm"+
"ögensberatung:企业:信息:嘉里大酒店:嘉里:.مصر‎:.قطر‎:广东:இலங்கை:இந்தியா:հայ:新加坡:.فلسطين‎:テスト:"+
"政务:xperia:xxx:xyz:yachts:yahoo:yamaxun:yandex:ye:yodobashi:yoga:yokohama:you:you"+
"tube:yt:yun:za:zappos:zara:zero:zip:zippo:zm:zone:zuerich:zw";
const tld = new Set(tlddata.split(":"));
function urlInfo(url) {
const split = url.split(".");
const split1 = split[0].split("#");
let p = split.length - 1;
if (split1.length === 2) split[0] = split1[1];
while (tld.has(split[p])) p --;
return {
domain: split[p],
subdomain: split.slice(0, p).join("."),
tld: split.slice(p + 1).join(".")
};
}
const test = [
"test#domain.com",
"test#domain.co.uk",
"test#subdomain.domain.com",
"test#subdomain.domain.co.uk",
"test#subdomain.domain.com.au",
"test#subdomain.domain.me"
];
test.forEach((url) => {
const info = urlInfo(url);
console.log(`${url} D=${info.domain} S=${info.subdomain ? info.subdomain : "None"} TLD:${info.tld}`);
});

Try this code..
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
else
{
if(isSubdomain(x))
alert("You entered a valid e-mail address with sub domain.");
}
}
function isSubdomain(url) {
var regex = new RegExp(/([\w-]+\.[\w-]+\.\w+)$/);
return url.match(regex); // make sure it returns boolean
}
</script>
</head>
<body>
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>

You can use the following script for this type of email validation.
var filter = /^\w+(?:\.\w+)*#\w+(?:\.\w+)+$/;

Related

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Javascript Regex Email Validation in Razer view

I am attempting to validate an email input that is created with an HTML helper class. The 'validateForm' method is being called properly everytime, but the if statement keeps failing. My two best theories are that my Regex, that I found here, is off due to me having to escape the '#' characters, or I'm not properly comparing it.
Thanks always!
Javascript:
function validateForm() {
var isValid = true;
var errorMessage = "";
var emailRegExp = /^(([^<>()[\]\\.,;:\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,}))$/;
var x = document.forms["Update"]["complaint.Responsible"].value;
if (x === null || x === "" || !emailRegExp.test(x)) {
errorMessage += "A valid 'Responsible' was not entered<br/>";
document.getElementById("Responsible").style.borderColor = '#F00';
alert("No! >:(");
isValid = false;
}
return isValid;
}
Form CSHTML:
#Html.TextBoxFor(model => Model.complaint.Responsible, new { #Class = "txtLong" })
Form HTML:
<form name="Update" onsubmit="return validateForm()" method="post" id="formBody" enctype="multipart/form-data">
<input class="txtLong" id="complaint_Responsible" name="complaint.Responsible" type="text" value="sdbsv rszaer gse er">
Update:
This is why I can't use a single '#' symbol
(one line - as is in code)
The ## is telling the regex engine that you expect two # symbols. Replace it with the pattern below:
var emailRegExp = /^(([^<>()[\]\\.,;:\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,}))$/;

Why does this think it's correct?

I'm new to js and I have this very simple code. It's supposed to be a login, and it's not working. I don't need any tips on making it better, I'm planning to do that when this starts to work.
<!DOCTYPE html>
<head> Sign-in </head>
<body>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em = "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa = "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</body>
</html>
What it's doing now is no matter what, it thinks that the correct e-mail and password were used. Could somebody help?
I've fixed your code up a bit. Some things to note.
You can't just put raw content in the <head>.
Your password is in the raw source of the page, so anyone can view the page source and see what the correct password is. That's an absolutely horrible design. Passwords should be passed to server side where they're checked for validity.
In C like programming language such as Javascript, == tests for equality and will return a boolean. The = sign assigns a value to a variable.
<!DOCTYPE html>
<head>
<title>Sign-in
</title>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em == "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa == "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</head>
<body>
</body>
</html>
Just one addition:
== checks value
=== checks value and type
Someone who deactivates js or doesn't support it like curl/wget and others, will not be stopped by this, except you load the whole website with js, what might be stupid cause of search engines might not index the content though.
Hope this helps.
fixed
var em = prompt("Enter E-mail Here:")
if(em === "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa === "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
You use a single = when you're assigning a variable a value. like var x = 1.
But if you want to check equality, use ===. like if(x ===1)

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

form still submitted after return false javascript

I'm having a little problem with a validation thing in javascript.
<form action="insert.php" id="form" name="form" method="post"
onSubmit="return validate()">
<pre>
Vul hier de/het E-mail adres(sen) in
<textarea name="email" rows="5" cols="50"></textarea><br>
Typ hier de E-mail
<textarea name="text" rows="5" cols="50"></textarea><br>
<input type="submit" name="Submit" value="Submit">
</pre>
</form>
As you can see here, I've got two textareas. In the upper one, you're supposed to enter one or multiple email addresses underneath eachother, and in the bottom textarea you're supposed to compose the email itself. Then, when you click on submit, it'll send the email to all those specified email addresses.
Now, I've made a validation for both textareas:
function explodeArray(emailID, delimiter) {
tempArray = new Array(1);
var Count = 0;
var tempString = new String(emailID);
while (tempString.indexOf(delimiter) > 0) {
tempArray[Count] = tempString.substr(0, tempString.indexOf(delimiter));
tempString = tempString.substr(
tempString.indexOf(delimiter) + 1,
tempString.length - tempString.indexOf(delimiter) + 1
);
Count = Count + 1
}
tempArray[Count] = tempString.replace("\r", "");
return tempArray;
}
function validate() {
var emailID = document.form.email;
var delimiter = "\n";
var emailArray = explodeArray(emailID.value, delimiter);
var textID = document.form.text;
var length = emailArray.length,
element = null;
for (var i = 0; i < length; i++) {
emailVar = emailArray[i];
if (emailVar == null) {
alert("Email-adres bestaat niet")
emailID.focus()
return false
}
if (emailVar == "") {
alert("Email-adres veld is leeg")
emailID.focus()
return false
}
if (checkEmail(emailVar) == false) {
emailVar.value = ""
alert("Ongeldig E-mail adres");
emailVar.focus()
return false
}
}
if ((textID.value == null) || (textID.value == "")) {
alert("E-mail textveld is leeg")
textID.focus()
return false
}
document.getElementById("form").submit();
return true
}
function checkEmail(hallo) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(hallo)) {
return true
}
return false
}
(I probably copied lots of irrelevant code as well, sorry for that, just copied the whole thing just in case...)
Now what does work is:
-it won't submit when both textareas are empty;
-it won't submit when the email addresses are valid but the bottom textarea is empty;
What doesn't work is:
-the form still submits when the email addresses are invalid, even when the bottom textarea is still empty.
I've been trying to figure out for hours what could possibly be wrong here, I googled and checked stackoverflow, but I really could not find anything. Could anybody tell me what I'm doing wrong here?
Thanks in advance.
You were using emailVar.focus(); which won't execute.
Here, fixed: Live Demo
if (checkEmail(emailVar) == false) {
alert("Ongeldig E-mail adres");
emailID.focus();
return false;
}

Categories

Resources