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.
Why the
forloop? And why set theblur()event inside of the loop like that?. I don’t understand your reasoning behind this. Instead of creating an array of ids, you can just give your fields a class an assign the event on that class.Edit:
The idea is to use objects instead of arrays and basically create one object with all the regex and errors and one function to evaluate the fields. Something like this: