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 {}
Related
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.
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)
}
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();
}
I have this script to send automatically the load information by email:
if(confirm('', 'Are you sure?') == true) {
// enviar mails
var emails = new Array();
if (getFormFieldValue('4469') != '') {
emails[0] = getFormFieldValue('4469');
}
if (getFormFieldValue('4470') != '') {
emails[1] = getFormFieldValue('4470');
}
if (getFormFieldValue('4471') != '') {
emails[2] = getFormFieldValue('4471');
}
var msgBody = 'blablabla' ;
var s = new SendMessage();
if(emails.length > 0) {
s.sendEmailMessage(emails, msgBody);
}
confirmForm();
}
As you can see, there are 3 mails, if I don't fill the first one, nothing happen, if i complete only the second or the thirst email also nothing. The only way to executed this script is filling the first email.
How can i fix this?
Thank you
Try using an array index variable to keep track of which entry in the email array you are populating. You want to always start with index 0, then 1, etc. regardless of which emails are filled in:
var emails == new Array();
var emailIndex = 0;
if (getFormFieldValue('4469') != '') {
emails[emailIndex ++] = getFormFieldValue('4469');
}
if (getFormFieldValue('4470') != '') {
emails[emailIndex ++] = getFormFieldValue('4470');
}
if (getFormFieldValue('4471') != '') {
emails[emailIndex ++] = getFormFieldValue('4471');
}
// emails should be populated now starting from index 0
If the form field values are always incremental from 4469-4471, you can also simplify and shorten your code with a for loop:
var emails = new Array();
var emailIndex = 0;
for (var fld = 4469; fld <= 4471; fld++)
if (getFormFieldValue(fld.toString()) != '')
emails[emailsIndex++] = getFormFieldValue(fld.toString());
EDIT: As noted by #Naren, this can be made even simpler by using Array.push:
var emails = new Array();
for (var fld = 4469; fld <= 4471; fld++)
if (getFormFieldValue(fld.toString()) != '')
emails.push(getFormFieldValue(fld.toString()));
Just use Array.push(), like this:
var x = getFormFieldValue(y);
if (x != '') emails.push(x);
This can be easily used iteratively: you can for example create an array with the field values to read from and loop over it.
I have a login box using a simple javascript login comparing usernames and passwords, before you all start I know about the security issues in using javascript for authentication. Here is the code
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters", "Jonathan Goss", "Lisa Cain", "Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
document.getElementById("mandatory1").value = un;
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
At the moment if the login is successful I'm posting the username to a hidden field which is then being used by a piece of a software. How do I associate the names in fnArray with the other correct username & password so that I can then grab associated full name and post that to the hidden field "mandator1" instead?
You can get the index of the correct user
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters, Jonathan Goss, Lisa Cain, Jenny Dempsey"];
var index = 0;
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
index = i;
break;
}
}
now you can access the correct data using
unArray[index];
// and so on for other arrays
Define a variable for full name, and set it if you have the valid user:
var fn = "";
/* ... */
valid = true;
fn = fnArray[i];
/* ... */
document.getElementById("mandatory1").value = fn;
Note: Actually you can check validity later on using fn. If it is empty string, then no user was logged in. This makes it have same purpose as valid, and more.
Try this.
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = -1;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters","Jonathan Goss","Lisa Cain","Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = i;
break;
}
}
if (valid != -1) {
alert ("Login was successful");
document.getElementById("mandatory1").value = fnArray[valid];
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
set mandatory1 when the login is successful based on i (in the for loop)