Javascript Regex Email Validation in Razer view - javascript

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,}))$/;

Related

Check if email address is Subdomain

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+)+$/;

Can anyone help me with JavaScript form validation?

I have created a validate function using JavaScript. I need a validation that tests that password field in a form to make sure it is:
At least 8 characters.
Contains a numeric value.
Contains an alphabetic value.
I just need an If statement inside my validate function
function Validate()
{
with(document.memberInfo) {
evt = new userInfo(username.value, password.value, email.value, firstname.value, lastname.value, age.value, description.value);
}
with(evt)
{
if((email.indexOf("#",0)==-1))
{
alert("The email must contain the # symbol.");
return false;
}
evt.printEvent();
}
return true;
}
using regx function you can validate ur form . here is the code .
var xstr="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$";
var str=Document.getElementById("id").value;
var ck=xstr.exec(str);
if(!ck || ck[0]!=str){
//code
}
you can use regex "/^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/" refer this link stackoverflow
JsFiddle
var regex = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/;
function getValue() {
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}
<input type="text" id="myinput" value="vexillology"/>
<button id="testBtn" onclick=test()>test</button>
<button id="matchBtn" onclick=match()>match</button>
Using regex is the way to go, but the more readable solution is probably:
function isValid(pass) {
return pass.length >= 8 && // at least 8 characters
/\d/.test(pass) && // contains a digit
/[A-Za-z]/.test(pass); // contains a letter
}
function isValid(pass) {
return pass.length >= 8 &&
/\d/.test(pass) &&
/[A-Za-z]/.test(pass);
}
var field = document.getElementById("password");
var output = document.getElementById("output");
field.onkeyup = function() {
output.innerHTML = isValid(field.value) ? "Valid" : "Not Valid";
}
<input type="text" id="password" placeholder="Enter password" />
<span id="output"></span>
Alternatively, you can put it all in one regex:
function isValid(pass) {
return /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(pass);
}
JSFiddle

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Using javascript for checking forms

here is my code:
<script>
function check(){
var error = '';
var name = document.forms['form1'].name.value;
var age = document.forms['form1'].age.value;
var checkname = new RegExp("^[a-zA-Z]{3,}$");
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
if (!checkname.test(name)) error+= 'Blad w nameniu\n';
if (!checkage.test(age)) error+= 'Blad w ageu\n';
if (error == '')
return true;
else {
alert(error);
return false;
}
}
</script>
<form name="form1">
<p>Name: <input type="text" name="name"></p>
<p>Age: <input type="text" name="age"></p>
<button type="button" onclick="check()">Send</button>
</form>
I have no idea why the given code simply doesn't work. There is no action at all. I have tried to change <button> to <input type="sumbit"> and <form onSubmit="check()"> but had no luck.
Fiddle
The problem is the regular expression for checkage
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
this needs to be
var checkage = new RegExp("^[1-9]{1}[0-9]{1}$");
And you can use firebug for firefox ( is a free add-on that helps you a lot).
Have a good day.
The problem of your code is the checkage regular expression. Instead of this :
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
You could try :
var checkage = new RegExp("/(^[1-9]?[0-9]{1}$|^100$)/");
But IMHO, regex is not the good way to validate the age. You should just write a simple function which check if the number is in between 0 - 100 range
Hope this helps !

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