Why is my Javascript form validation not working properly? - javascript

Why is my validation failing on second attempt here? On first attempt the validation works fine, but on the second run, it will accept inappropriate values in the email field. The first two fields work fine, but the third field will accept any text after the first run. However it only validates if I change the value in the email field, otherwise it will keep displaying the error and failing to validate like it should.
function validate(){
clearErrors();
var errorFlag = true;
var name = document.getElementById("name");
nameVal = name.value;
if(nameVal.length === 0){
var nameError = document.getElementById("nameError");
nameError.style.display = "block";
errorFlag = false;
}
var phone = document.getElementById("phone")
var phoneVal = phone.value;
if(isNaN(phoneVal) || (phoneVal < 1000000000 || phoneVal >10000000000)){
errorFlag = false;
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "block";
}
var email = document.getElementById("email");
var emailVal = email.value;
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
errorFlag = false;
var emailError = document.getElementById("emailError");
emailError.style.display = "block";
}
return errorFlag;
}
function clearErrors(){
var nameError = document.getElementById("nameError");
nameError.style.display = "none";
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "none";
var emailError = document.getElementById("emailError");
emailError.style.display = "none";
}

Your validator will fail on the email, because you are feeding a string to .match, when it needs a regex.
You also have to call .match on the email itself, with the regex as the argument.
You also need to negate the return value to check if it does not match, or use .test.
This bit:
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
Should be replaced with:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!emailVal.match(re)){
Of if you can't use a regex literal for some reason:
var re = new RegExp("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$", "i");
if(!emailVal.match(re)){
Or using .test instead of .match:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!re.test(emailVal)){
Note the i for case-insensitive matching, so emails don't have to be entered in all-caps.

Related

How to allow validation for multiple email addresses using javascript

I am using javascript to validate my page, I have done the validation for email which should follow the basic rules of email id. But I need the validation to allow multiple email addresses. Can anyone please help in adding this. Thanks in advance.
Here is JS Code:
function function1(){
var exp = /^(([^<>()[\]\\.,;:\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 emailid = document.getElementById('mailid').value;
if(emailid == '' || emailid == null){
document.getElementById('error4').innerHTML = "* Enter Email ID";
document.getElementById('mailid').focus();
return false;
}else{
document.getElementById('error4').innerHTML = "";
}
if (!exp.test(emailid)) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
}
You could do something like this:
var emails = emailid.split(",");
emails.forEach(function (email) {
if(!exp.test(email.trim()) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
});
You should split your emailid string into an array and then check the emails one by one
var emails = emailid.split(',');
You can know more about the split method here http://www.w3schools.com/jsref/jsref_split.asp
Assuming the addresses are separated by comma you could do something like this:
(untested but you should get the idea)
var theString = "an.address#domain.ext, an.other.address",
stringProper = theString.replace(/\s/g,''),
addresses = stringProper.split(','), //creates an array of every email
allValid = true;
for (var i = addresses.length - 1; i >= 0; i--) {
if (addresses[i] == 'an.other.address') {
isValid = true;
} else {
isValid = false;
}
if(!isValid) {
allValid = false;
break;
}
};
function isEmail (theString) {
var exp = /^(([^<>()[\]\\.,;:\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 exp.test(theString)
}

JavaScript error with splitting string into array

I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!
You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}
Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}

getting JavaScript to execute multiple if statements

How do I get the below JavaScript code to execute multiple if statements regardless of the if statement above being true or false.
here is the code
var uname = document.getElementById("pword1").value;
var pword = document.getElementById("cPassword").value;
var passReq = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\"\.\[\]_£|`¬':;~{}<>()#?!#$%^&*-]).{8,20}$";
var matchCol = "#009900";
var noMatchCol = "#CC0000";
var noBg = "#FFFFFF";
if (uname.length < 1 || pword.length < 1){
cPassword.style.backgroundColor = noBg;
match = "";
}else if(passReq.test(uname)){
DIMR = "Does Meet Requirements";
}else if(!passReq.test(uname)){
DIMR = "Does Not Meet Requirements";
}else if (pword1.value == cPassword.value){
match = "Match!";
cPassword.style.backgroundColor = matchCol;
} else if (pword1.value != cPassword.value){
match = "No Match!";
cPassword.style.backgroundColor = noMatchCol;
}
document.getElementById("combination").innerHTML = match;
document.getElementById("reqMeeting").innerHTML = DIMR;
}
I have 2 input boxes. "Password" and "Confirm Password". I want various to happen including: if nothing is entered no messages are returned, if the passwords don't match then the confirm password turns red, if they do match turns green, if the value does not fit the regular expression then send another message to the screen saying "does not meet requirements, if it does match expression then send a different messsage to the screen saying "does meet requirements".
You probably want it to be more like:
var uname = document.getElementById("pword1").value;
var pword = document.getElementById("cPassword").value;
var passReq = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\"\.\[\]_£|`¬':;~{}<>()#?!#$%^&*-]).{8,20}$";
var pwReqExp = new RegExp(passReq);
var matchCol = "#009900";
var noMatchCol = "#CC0000";
var noBg = "#FFFFFF";
if (uname.length < 1 || pword.length < 1){
cPassword.style.backgroundColor = noBg;
match = "";
}
if(pwReqExp.test(uname)){
DIMR = "Does Meet Requirements";
}else {
DIMR = "Does Not Meet Requirements";
}
if (pword1.value == cPassword.value){
match = "Match!";
cPassword.style.backgroundColor = matchCol;
} else {
match = "No Match!";
cPassword.style.backgroundColor = noMatchCol;
}
document.getElementById("combination").innerHTML = match;
document.getElementById("reqMeeting").innerHTML = DIMR;
}
update:
added new RegExp
var pwReqExp = new RegExp(passReq);
// ...
pwReqExp.test(uname)
// ...
Javascript, like java evaluates if statements and "links" them to the previous one, so you should end the if and use this syntax:
if (expression) {
//code goes here
}
else {}
if (other expression) {
//more code
} else {}
if (yet another expression) {
//even more code
} else {}

Why is my div not updating properly?

So my code basically is to tell users what's wrong in their registration, everything works but one thing. The Div should update the text field to say what's wrong with their registration, but it is not, here is my JavaScript
window.onload = initPage;
submitBtn = document.getElementById("submit");
errorText = document.getElementById("errortext");
function initPage() {
document.getElementById("password2").onkeyup = checkPassword;
document.getElementById("password2").onblur = checkPassword;
document.getElementById("email2").onkeyup = checkEmail;
document.getElementById("email2").onblur = checkEmail;
submitBtn.disabled = false;
}
function checkPassword() {
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
if (password1 != password2) {
document.getElementById("password1").className = "denied";
document.getElementById("password2").className = "denied";
submitBtn.disabled = true;
document.getElementById("submit").className = "denied";
errorText.innerHTML = "Passwords do not match.";
} else {
document.getElementById("password1").className = "password2";
document.getElementById("password2").className = "password2";
document.getElementById("submit").className = "button1";
submitBtn.disabled = false;
errorText.innerHTML = "";
}
}
function checkEmail() {
var email1 = document.getElementById("email1").value;
var email2 = document.getElementById("email2").value;
if (email1 != email2) {
document.getElementById("email1").className = "denied";
document.getElementById("email2").className = "denied";
submitBtn.disabled = true;
document.getElementById("submit").className = "denied";
errorText.innerHTML = "Emails Do Not Match.";
} else {
document.getElementById("email1").className = "regtext";
document.getElementById("email2").className = "regtext";
submitBtn.getElementById("submit").disabled = true;
document.getElementById("submit").className = "button1";
errorText.innerHTML = "";
}
}
here is my div
<tr><td colspan="2"><div id="errortext"></div></td></tr>
You're probably trying to access that div before the DOM is fully constructed. Put that code in with the initPage function. You'll need a variable outside of the scope of that function so your other functions can access them. You should put all of this in a closure to avoid creating global variables.
Ex:
(function(){
var submitBtn;
var errorText;
function initPage() {
submitBtn = document.getElementById("submit");
errorText = document.getElementById("errortext");
document.getElementById("password2").onkeyup = checkPassword;
document.getElementById("password2").onblur = checkPassword;
document.getElementById("email2").onkeyup = checkEmail;
document.getElementById("email2").onblur = checkEmail;
submitBtn.disabled = false;
}
// This next line should be under the declaration above
window.onload = initPage;
// ...
})();
You have to fetch the element by id and then sets its inner html.
document.getElementById("errorText").innerHTML = "Emails Do Not Match.";
and do the same where ever you are using errorText.innerHTML directly.

how to compare the value

This my code
I am getting email address from database through ajax and mysql it is giving me value in . so in below FUNCTION comparing() i am retriving data from span to compare with the textfield data. but it is not comparing properly.
Please help me out
function validate(pageForm)
{
/************Getting error values in return values***********************/
var returncomparing = "";
/*********************************/
//FIELD WHICH YOU HAVE TO VALDATE
returncomparing += comparing(pageForm.email);
/********************************************/
if (returncomparing != "")
{
document.getElementById('error').innerHTML = returnIndustry;
}
return false;
}
After giving correct EMAIL still it is giving Error ... (Please Provide Login User ID)
function comparing(pageForm){
var error = "";
// var fetchedEmail=document.forms["pageForm"]["email_fetch"].value;
var em=document.forms["pageForm"]["email"].value;
//var emai = document.getElementById('emlTst').value;
var email = document.getElementById('txtHint').innerHTML;
//document.getElementById('emlTst').value = email;
if(em != email){
document.getElementById('error_email2').innerHTML="Please Provide Login User ID";
pageForm.style.borderColor = 'red';
error='5';
}
else if(em == email){
document.getElementById('error_email2').innerHTML="";
error = "";
}
else {
document.getElementById('error_email2').innerHTML="";
pageForm.style.borderColor = '#c7c7c7';
}
return error;
}
/*************************************************************/
var em = $('#email').val().toLowerCase();
var email = $('#txtHint').val().toLowerCase();

Categories

Resources