I have built a login system with LocalStorage on my website and would like to build an error message if I enter it incorrectly. Since I have already got help for the email error on another page, I would like to add the message that appears there to my other error messages. Is there a solution to apply the Email Error message to other elements or do I have to style and rebuild all messages? If there is a possibility I would like it (below in the code) for the functions "checkRegisterEnter" and "checkRegisterPassword" for the alert replacement. The email check can be seen below.
Javascript code:
function checkRegisterEnter(){}
if(givenname.value == 0){
alert("Name field is Empty!")
}
function checkRegisterPassword(){
if(password.value !== password2.value) {
alert('The first password does not match the second!')
}
}
//Email_Check
const checkrform = document.getElementById("register.form")[0];
const checkremail = document.getElementById("ri3");
let remailerror = checkremail;
while ((remailerror = remailerror.nextSilbing).nodeType != 1);
const remailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
function addEvent(remailelement,remailevent,callback){
let previousEventCallBack = remailelement["on"+remailevent];
remailelement["on"+remailevent] = function (e) {const remailoutput = callback(e);
}
};
(Translated with Google Translate, errors may be included.)
Edit: Problem has still not been solved. Would be helpful if someone knew the answer.
Errors in JavaScript can be displayed without the use of alert boxes but using the alert box is the traditional way to do that. We can show errors with two methods without using the alert box
Related
This script works. It has user id 4 which I am adding their email address to check the google admin API. The resolved column[10] is where managers approve requests. Because some of these usernames are not correctly entered, I was looking for a way to check if they were actually correct user ids. Both .setValue() lines work under try and catch, they also error on same users. I am trying to understand where the actual validation is happening. I guess I am trying to figure how the script knows to check the primary email address? Hope that makes sense.
function getNames() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getActiveSheet();
var values = sheet.getDataRange().getValues();
for(var i = 1; i < values.length; i++){
var data = values[i];
var resolved = data[10];
if(resolved === ""){
try{
var email = sheet.getRange(1+i,4).getValues() + '#buisness.com'
var user = AdminDirectory.Users.get(email);
var name = user.name.fullName;
sheet.getRange(1+i, 5).setValue('Yes this is an employee');//How does this work?
//sheet.getRange(1+i, 5).setValue(name);//This works which I expect
}
catch(errors){
sheet.getRange(1+i,5).setValue(errors);
}
}
}
}
The validation happens through the AdminDirectory.Users.get() function with the help of the try and catch statements.
Admin SDK Directory Service/Get User
This API function gets a user by their email address. If the email address exists, all their data will be logged as a JSON string. Otherwise, it will return an error.
Try and Catch
The try and catch statements belong under JavaScript Errors. The try statement will run a code block that you place in it. If it encounters any error, it will trigger the catch statement (which usually displays the error messages.
Your Code
Your code checks for the validity of the email address with the use of the AdminDirectory.Users.get() function inside the try statement. If the function fails, it returns an error which triggers the catch statement (which usually displays the error messages).
References:
Admin SDK Directory Service/Get User
JavaScript Errors
I'm fairly new to JS & React and I'm using React Hook Form
I have to check if the Website entered into the Website field in my form exists or not.
If the URL doesn't exist I have to show an error message as "Website not available" under the Website field which will get rendered using a FormError component.
(This is a First Name field but since I'm using a common TextField Component it should work here as well)
So, I'm using "url-exists" package to test if a website URL exists and if the website doesn't exists it should generate an error as "Website not available".
I'm using this code to implement.
const websiteCheck = (value) => {
let str = value;
let message = "";
let urlCheck = str.indexOf("http://") == 0 || str.indexOf("https://") == 0;
if (!urlCheck) {
console.log("Protocol doesn't exist!");
str = "http://" + str;
} else {
console.log("Protocol exists!");
}
urlExists(str, function (err:any, exists:any) {
if (!exists) {
message = "Website doesn't exists!" //Just for testing
console.log("Not available: ", str, exists);
} else {
message = "Website exists!"
console.log("Available: ", str, exists);
}
// console.log(exists); // true
});
return message;
}
And I'm calling it as :
return(
.....
<TextField
key={fieldName}
id={fieldName}
.......
inputRef={register({
websiteCheck(value)
........
/>
This should ideally work but it's giving me "Not available" message in console.log() even if I enter a correct & valid URL.
And it still won't render the message I set.
What I found so far from debugging is :
When I submit my form my entered URL is accepted but it won't enter my if(!exists)..else block and I get "Not available" in console.
The second time it's submitting null value (or space idk) which enters the if(!exists)...else block and also says "Not available"
What should I do to get this resolved?
You have to correct a few things here to make it work:
you should use <Controller /> when using a Material UI <TextField />, see this section in the docs for more infos about it
you need to use the validate function provided by RHF via the rules prop of the <Controller />, check here for all validation options (register and rules use the same interface for validations)
urlExists uses a callback, so you need to wrap the call to urlExists into a Promise and set it as the return value of your websiteCheck function. Right now you are returning a string before the callback is even executed. The important thing here is to also make your websiteCheck function async, so that the Promise will get resolved (the validate function from RHF supports using a async function)
it's also important to note, that you have to return true for the validate function if the entered value is correct. If not use a string for the error message
I have written a simple javascript function which which will mask all credit card nos digits except the last four digits for agent login and for any other login(admin/manager) it will display all the credit card
digits(12) without masking.
I am facing two issues here: one - it is masking for everyone irrespective of agent or manager login. Another one: the masking is such that the last four digits shows at front and the remaining is shown a complete blank space, for better understanding I am providing both code and screenshot of the masking.
// JavaScript source code
function RetrieveLoggedInD365UserSecurityRoles(executionContext) {
var roleName = "Agent";
//will retrieve the credit Card Number from the form
var formContext = executionContext.getFormContext();
var creditCardNum = formContext.getAttribute("cts_creditcardnumber").getValue();
var duplicatecreditCardNum = creditCardNum;
//
//to retrive the global user context from the d365 security profile
var globalContext = Xrm.Utility.getGlobalContext();
var userRoles = globalContext.userSettings.roles;
//using regex it will mask the digits of credit card Numbers
userRoles.forEach(function hasRoleName(item) {
if (item.name == roleName) {
alert("i m in!!")
var replacedCreditCardNum = creditCardNum.replace(/\d(?=\d{4})/g, "x");
formContext.getAttribute("cts_creditcardnumber").setValue(replacedCreditCardNum);
};
if (item.name != rolename) {
formContext.getAttribute("cts_creditcardnumber").setValue(duplicatecreditCardNum);
};
}
);
}
It should have shown as "xxxxx-xxxx-0123" and its masking for all logins irrespective of agent or administrator
Your code has a flaw - both if statements will execute on every role and switch the masking, thats why the behavior is confusing you.
You should have a flag and default it to false, then iterate and check - only when the necessary role is returned in the user roles list - you should set the flag as true.
Then based on flag, you should mask/unmask it.
(Though this should have been done in server side itself as the field level security cannot be done for partial masking and not on client side as a best practice to avoid exposed in client side code, Maybe retrieve/retrieve multiple plugin is an option at the cost of performance impact)
var userHasAccess = false;
userRoles.forEach(function hasRoleName(item) {
if (item.name == roleName) {
alert("I'm in!!")
userHasAccess = true;
};
});
if(userHasAccess == false){
var replacedCreditCardNum = creditCardNum.replace(/\d(?=\d{4})/g, "x");
formContext.getAttribute("cts_creditcardnumber").setValue(replacedCreditCardNum);
}
else{
formContext.getAttribute("cts_creditcardnumber").setValue(duplicatecreditCardNum);
}
For regex us some online tester to see it in action.
I have been trying to automate Lotus Notes mail fillup from a browser interface.
After refering to Richard Schwartz's answer, i came up with this piece of code using the Lotus.NotesSession class.
function SendScriptMail() {
var mToMail = document.getElementById('txtMailId').value
var mSub = document.getElementById('txtSubject').value
var mMsg = document.getElementById('txtContent').value
var Password = "yyy"
alert("1");
var MailFileServer = "xxx.com"
var MailFile = "C:\Program Files\IBM\Lotus\Notes\mail\user.nsf"
alert("2")
var Session;
var Maildb;
var UI;
var NewMail;
var From = "user#xxx.com"
try {
alert("3")
// Create the Activex object for NotesSession
Session = new ActiveXObject("Lotus.NotesSession");
alert("4")
if (Session == null) {
throw ("NoSession");
} else {
Session.Initialize(Password);
// Get mail database
Maildb = Session.GetDatabase(MailFileServer, MailFile);
alert("5")
if (Maildb == null) {
throw ("NoMaildb");
} else {
NewMail = MailDB.CreateDocument();
if (MailDoc == null) {
throw ('NoMailDoc');
} else {
// Populate the fields
NewMail.AppendItemValue("Form", "Memo")
NewMail.AppendItemValue("SendTo", mToMail)
NewMail.AppendItemValue("From", From)
NewMail.AppendItemValue("Subject", mSub)
NewMail.AppendItemValue("Body", mMsg)
NewMail.Save(True, False)
NewMail.Send(False)
}
}
}
} catch (err) {
// feel free to improve error handling...
alert('Error while sending mail');
}
}
But now, alerts 1,2,3 are being trigerrd, and then the counter moves to the catch block. The lotus notes session is not being started.
In a powershell script that I was previously looking at there was a code regsvr32 "$NotesInstallDir\nlsxbe.dll" /s that was used before the Session = new ActiveXObject("Lotus.NotesSession");. Is there something similar in javascript too, if so how do i invoke that dll.
I think I've realised where I am going wrong. According to me, upto alert("5") things are good. But since Lotus.NotesSession doesn't have a CreateDocument() method, it is throwing the error. I am not sure how to create the document and populate the values though.
Since you've chosen to use the Notes.NotesUIWorkspace class, you are working with the Notes client front-end. It's running, and your users see what's happening on the screen. Are you aware that there's a set of back-end classes (rooted in Lotus.NotesSession) instead of Notes.NotesSession and Notes.NotesUIWorkspace) that work directly with Notes database data, without causing the Notes client to grab focus and display everything that you're doing?
Working with the front-end means that in some cases (depending on the version of Notes that you are working with) you're not going to be working directly with the field names that are standard in Notes messages as stored and as seen in the back-end. You're going to be working with names used as temporary inputs in the form that is used to view and edit the message. You can see these names by using Domino Designer to view the Memo form.
Instead of using 'SendTo', try using:
MailDoc.Fieldsettext('EnterSendTo', mToMail)
Regarding the Body field, there's no temporary field involved, however you haven't really explained the difficulty you are having. Do you not know how to display the interface that you want in the browser? Do you not know how to combine different inputs into a single FieldSetText call? Or are you just dissatisfied with the fact that FieldSetText can't do any fancy formatting? In the latter case, to get more formatting capability you may want to switch to using the back-end classes, which give you access to the NotesRichTextItem class, which has more formatting capabilities.
I'm using the built-in api for scripting against Google Spreadsheets to send some booking confirmations, and currently my script breaks if someone has filled in an invalid email. I'd like it to just save some data to a list of guests that haven't been notified, and then proceed with looping through the bookings.
This is my current code (simplified):
// The variables email, subject and msg are populated.
// I've tested that using Browser.msgBox(), and the correct column values are
// found and used
// The script breaks here, if an incorrect email address has been filled in
MailApp.sendEmail(email, subject, msg)
According to the documentation the only two methods on the MailApp class are to send emails and check the daily quota - nothing about checking for valid email addresses - so I don't really know what criteria must be fulfilled for the class to accept the request, and thus can't write a validation routine.
If you need to validate email addresses beforehand, create a blank spreadsheet in your drive. Then, run the function below, changing the testSheet variable to point to the spreadsheet you created. The function will do a simple regex test to catch malformed addresses, then check if the address is actually valid by attempting to temporarily add it as a viewer on the spreadsheet. If the address can be added, it must be valid.
function validateEmail(email) {
var re = /\S+#\S+\.\S+/;
if (!re.test(email)) {
return false;
} else {
var testSheet = SpreadsheetApp.openById(arbitrarySpreadsheetInYourDrive);
try {
testSheet.addViewer(email);
} catch(e) {
return false;
}
testSheet.removeViewer(email);
return true;
}
}
regex from How to validate email address in JavaScript?
Stay calm, catch and log the exception and carry on:
try {
// do stuff, including send email
MailApp.sendEmail(email, subject, msg)
} catch(e) {
Logger.log("Error with email (" + email + "). " + e);
}
On the otherhand, avoid Checking email in script and get rid of loses quota or try-catch etc. I used that I got a valid email when user attempt to send an email, by signing him in an email and got that email:
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String s = account.getEmail(); // here is the valid email.
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
}
Full procedure Here.
This answer is much later than this question was asked, but I piggy-backed off of remitnotpaucity's answer based on a comment in his answer. It does basically the same thing, adding the email to the spreadsheet and catching the error, however in my case it creates a new spreadsheet, attempts to add the user, and then after attempting to add the user, deletes the spreadsheet. In both cases, that the email is a valid email or not, it deletes the newly created spreadsheet.
Some things to note:
I am not as familiar with regular expressions, so I only check to see if the # symbol is within the email read into the function, and do not check for whitespaces.
I believe that even if it passes the first if-statement, even if it's not a valid email, an error will still be thrown and caught because Google will still catch that it's not a valid email, making the first if-statement redundant
If you are trying to validate an email outside your company, I'm unsure how it would react, so be fore-warned about that
This validation method takes a few seconds because you are creating and then deleting an email all within a single function, so it takes a fair bit longer than remitnotpaucity's
Most importantly, if you are able to, I would use an API. I believe that this one would work perfectly fine and should be free, it just may take some extra elbow-grease to get to work with GAS.
function validateEmail(email){
let ss = SpreadsheetApp.openByUrl(SpreadsheetApp.create('Email Validation Spreadsheet', 1, 1).getUrl())
if(!new RegExp('[#]').test(email)){
return false
} else{
try{
ss.addViewer(email)
} catch(e){
setTrashed()
return false
}
setTrashed()
return true
}
function setTrashed(){
DriveApp.getFilesByName('Email Validation Spreadsheet').next().setTrashed(true)
}
}