Javascript e-mail validation of specific domains - javascript

I can’t figure out what is missing so that when e-mail is valid it will skip the last invalid message and move to next item on form for validation:
enter code here
if (document.form1.email.value.length > 0) {
var tst = document.form1.email.value;
var okd = ['bankofamerica.com','baml.com','magner.com','ml.com','ust.com','ustrust.com']
for (var i = 0; i < okd.length; i++) { okd[i] == okd[i].toLowerCase() }
var emailRE = /^[a-zA-Z0-9._+-]+#([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
var aLst = emailRE.exec(tst)
if (!aLst) {
alert(tst + ' is not a valid e-mail')
} else {
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
// alert(aLst[1] + ' is allowed');-->
}
}
if (i == okd.length) alert(aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.')
document.form1.email.select();
return false;
}
}

I'd recommend placing this code into a function, maybe named ValidateEmail().
In your loop: if you've determined the email is valid, return true;. This will prevent further execution. If that domain doesn't match, have it continue looping to check the others.
If the loop completes without returning true, you'll know it didn't match anything so return false; at the very end.
EDIT: Use try/catch instead:
if (document.form1.email.value.length > 0) {
var tst = document.form1.email.value;
var okd = ['bankofamerica.com','baml.com','magner.com','ml.com','ust.com','ustrust.com']
for (var i = 0; i < okd.length; i++) { okd[i] == okd[i].toLowerCase() }
try {
var emailRE = /^[a-zA-Z0-9._+-]+#([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
var aLst = emailRE.exec(tst)
if (!aLst)
throw (tst + ' is not a valid e-mail');
// isValidDomain will be changed to 'true' only if it matches an item in the array
var isValidDomain = false;
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
isValidDomain = true;
// We break here because a match has been found - no need to compare against the other domain names.
break;
}
}
if(!isValidDomain)
throw (aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.');
// If execution reaches here, you know it passed both tests!
return true;
}
catch(err) {
// This code block runs whenever an error occurs
alert(err);
document.form1.email.select();
return false;
}
}
throw basically acts like a goto command. It will jump directly to the catch(err) portion of the code.
More info about try, catch, and throw:
http://www.w3schools.com/js/js_try_catch.asp
http://www.w3schools.com/js/js_throw.asp

Thank you very much Colin!
I had to remove the following 2 lines to avoid halting the code from running on to next validation field:
isValidDomain = true;
// We break here because a match has been found - no need to compare against the other domain names.
// break - exits code from running on down to next item on page
}
}
if (!isValidDomain)
throw (aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.');
// If execution reaches here, you know it passed both tests!
// return true; - was not needed, stops code from running on page
}
catch (err) {

Related

Insert Logging In Functions ASP.NET

I have an .ascx containing javascript and div elements.
I want insert a log statement inside a function for troubleshooting.
May I know how can I achieve it?
Below is my code snippet:
function SaveGroupCheck() {
var isValid = true;
var haveError = false;
var schedule = document.getElementById("<%=ddlExecutionSchedule.ClientID%>").value;
//INSERT LOGGING HERE - Value of 'schedule'//
if (schedule == "Weekly")
{
var xday = document.getElementById("<%=chkSelectDay.ClientID%>");
var checkbox = xday.getElementsByTagName("input");
var counter = 0;
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked) {
counter++;
}
}
//INSERT LOGGING HERE - Value of 'counter'//
if (counter < 1) {
$("#chkSelectDay").addClass('errorbox');
$("#divSelectDay").addClass('has-error has-feedback');
$("#lblSelectDay").addClass('has-error has-feedback');
haveError = true;
}
else {
$("#chkSelectDay").removeClass('errorbox');
$("#divSelectDay").removeClass('has-error has-feedback');
$("#lblSelectDay").removeClass('has-error has-feedback');
}
}
//INSERT LOGGING HERE - Value of 'haveError'//
Below is a log which I attempted but failed. I will use a try-catch if the error info needs to be provided.
var logFileName = ConfigurationManager.AppSettings["logpath"] + "Debug_" + DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".log";
var itemPerPage = document.getElementById("<%=txtItemsPerPage.ClientID%>").value;
Log(DateTime.Now.ToString("ddMMyyyy_hhmmss") + " - itemPerPage = " + itemPerPage);
*logpath configured in app.config.
Thank you for your time.
To log any javascript variables you can use :
console.log("Hello I'm the variable value");
and open chrome console to see the value.
If you want to send variable value to server you must go to ajax call by calling server method for logging.
I hope that I understood your question.

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

Local variables giving global trouble

I'm a JS super n00b.
I asked about an aspect of this problem in this post (Puzzling behavior from IF ( ) statement) on IF statements but it looks like the actual issue is related to the scope of a variable I've created. It seems that after declaring (what I think is) a global variable, other functions in the code cannot access the variable.
I'm doing JS project/program that prompts a user to input a word and the program reverses the word input.
In the previous post (PP) a user correctly determined that I was getting the 'false' console message (see code) no matter what the length of the word input because I was assigning value the variable when the page loads but not reading it again when the user clicks the button on the page.
If the variable 'word' is local I'm only able to get a 'false' console message and when the variable 'word' is global I'm only able to get a 'ReferenceError.'
Any ideas anyone has are greatly appreciated.
See JS code below:
var word = document.getElementById('wordChoice').value;
var lttrs = [];
function flipFail () {
alert("Please enter a word of at least two characters.");
console.log(false);
var inputErrArr = ['has-error', 'has-feedback'];
var inputErrFdbk = ['glyphicon', 'glyphicon-remove'];
wordChoice.style.backgroundColor = "#FFDBAA";
for (var i = 0; i < inputErrArr.length; i ++) {
addClass(wordInput, inputErrArr[i]);
}
for (var i = 0; i < inputErrFdbk.length; i ++) {
addClass(glyph, inputErrFdbk[i]);
}
document.getElementById('wordChoice').value = " ";
} // END flipFail()
function flipSuccess (){
for (var i = 0; i < word.length; i ++) {
lttrs.push(word.charAt(i));
}
lttrs.reverse();
var reversedWord = lttrs.join('')
alert("Your reversed word is: " + reversedWord);
console.log(true);
document.getElementById("flip").innerHTML = "Flip Again!";
document.getElementById('wordChoice').value = " ";
} // EN flipSuccess ()
function flipChk () {
if (word.length < 2) {
flipFail ();
} else {
flipSuccess ();
}
}
See fully implemented code here: http://supsean.com/supsean/flipr/flipr.html
You need to set word in flipChk(). You're setting it when the page is first loaded, before the user has entered anything into the form, not when the user clicks on the Flip button.
Then, instead of using a global variable, pass it as an argument to the function. In general, avoid using global variables unless you really have to.
function flipChk () {
var word = document.getElementById('wordChoice').value;
if (word.length < 2) {
flipFail ();
} else {
flipSuccess (word);
}
}
function flipSuccess (word){
var lttrs = [];
for (var i = 0; i < word.length; i ++) {
lttrs.push(word.charAt(i));
}
lttrs.reverse();
var reversedWord = lttrs.join('')
alert("Your reversed word is: " + reversedWord);
console.log(true);
document.getElementById("flip").innerHTML = "Flip Again!";
document.getElementById('wordChoice').value = " ";
} // EN flipSuccess ()

How to get my loop to start from the beginning after error detected

I am trying to get my loop to restart when it comes across an user input error. I need it to restart at the very beginning and not just the last question.
So below when it says validImput = false this is where I am trying to get it to restart.
{
var validInput = true;
var start = confirm('Add item to shoping cart');
if (start == true) {
// ask first question
var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
if (isNaN(orderProductCodeArr)) {
alert("input is not a valid number");
validImput = false
} else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
alert("code does not match any item");
validInput = false;
}
// ask second question
else if(validInput == true) {
var item = PRODUCT_LIST[orderProductCodeArr];
alert("item is: " + item);
}
// get quantity input
var quanityArr = parseInt (prompt('Enter quality amount'),10);
if (isNaN(quanityArr)) {
alert("input is not a valid number");
validInput = false;
}
} else {
document.writeln('still to come')
}
}
The usual method of starting something over is some sort of loop construct, often using while like this:
while (true) {
// your loop code here
// you can use break; to break out of the while loop
// anywhere to stop repeating
// you can use continue; to jump to the next iteration immediately
}
Or, sometimes you use a loop condition like this:
var doAgain = true;
while (doAgain) {
// within the loop, you set doAgain to false when you are done
// and don't want to repeat the loop again
}
try
function test()
{
for(var s=0;s<5;s++)
{
try
{
//body of the for loop
}catch(e){s=0;}
}
}

Get error message of page validators for particular group by javascript in asp.net

I am trying to write javascript function in which I want to show the error message of the of the invalid fields of the validatiors whose groupname is given.
Basically I am having some different group of validators and want to show there error message in alert if value entered is in valid for the group whose button is pressed using common function.
I am using following code:
function check(group) {
if (Page_ClientValidate(group)) {
return true;
}
else {
var message="";
for (i = 0; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isValid) {
message = message + Page_Validators[i].Errormessage+ "\n";
}
}
alert("Enter following fields marked with * or Invalid Data\n"+message);
return false;
}
I want to run following section of code for particular group of validators:
var message="";
for (i = 0; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isValid) {
message = message + Page_Validators[i].Errormessage+ "\n";
}
}
alert("Enter following fields marked with * or Invalid Data\n"+message);
return false;
}
If i understood correctly, a simple switch statement would do the trick
for (i = 0; i < Page_Validators.length; i++) {
switch(Page_Validators[i].validationGroup)
{
case "MyGroup1":
// your javascript code
break;
case "MyGroup2":
// your javascript code
break;
default:
// your javascript code
break;
}
}
If you need to see the javascript object properties, set a breakpoint in the javascript and debug using Visual Studio

Categories

Resources