I am trying to create a javascript - jQuery form validator.
I have an array with the regular expressions for each field, an array with the id of each field, and a third one with the error message I want to show the user if the entered value does not match the regular expression for each input.
I am trying to run a loop, and within it, create the .blur event listeners for every one of my form inputs.
My code is here:
$(function(){
signUp()
})
function signUp(){
var err = new Array();
var regex = new Array();
var mess = new Array();
var nm = new Array();
var i = 0;
// regex definitions //
regex[0] = /^[a-zA-Z]+([s][a-zA-Z]+)*$/;regex[1] = regex[0]; //onoma , epwnimo
regex[2] = /^(d){10}$/;regex[3] = /^([a-zA-Z-]+s)+d{1,5}$/; //tilefwno , dieuthinsi
regex[4] = /^[w-.+]+@[a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/;regex[5] = regex[4]; // email
regex[6] = /^[a-zA-Z0-9]+([\_]?[-]?[a-zA-Z0-9]+)*$/;regex[7] = regex[6]; // password
// message definitions //
mess[0] = 'Το ?νομα πρ?πει να αποτελε?ται μ?νο απο λατινικο?? χαρακτ?ρε? και κεν?!';
mess[1] = 'Το επ?νυμο πρ?πει να αποτελε?ται μ?νο απο λατινικο?? χαρακτ?ρε? και κεν?!';
mess[2] = 'Το τηλ?φωνο πρ?πει να αποτελε?ται απ? 10 ψηφ?α!';
mess[3] = 'H διε?θυνση πρ?πει να περι?χει οδ? και αριθμ? με λατινικο?? χαρακτ?ρε?, π.χ. Ellinos Stratiwtou 13!';
mess[4] = 'Εισ?γετε μια ?γκυρη διε?θυνση email!';mess[5] = mess[4];
mess[6] = 'Το password πρ?πει να αποτελε?ται απο λατινικο?? χαρακτ?ρε?, αριθμο??, _ και -';mess[7] = mess[6];
// div name definitions //
nm[0] = '#onoma';nm[1] = '#epwn';nm[2] = '#tele';nm[3] = '#addr';
nm[4] = '#ema';nm[5] = '#emai';nm[6] = '#pasw';nm[7] = '#conpass';
for(;i<8;i++){
$(nm[i]).blur(function(){
alert(nm[i])
})
}
}
I was hoping the code above would alert me the name of the form input that triggered the blur event, but all I get is undefined, and when I try to alert(i)
, within the .blur
function, it always shows 8, no matter what field I run this on.
What am I doing wrong?
Note: I have not posted my html since it's just a form, but I will post it if needed.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…