Can't validate emails using anything (Node JS) - node.js

I'm trying to find a way to validate emails, but everything I use will either return false all of the time, or return true all of the time. I've tried deep email validator; which returns false, email validator; which returns true, and another method that has a lot of characters; which also returns true.
I'm not too sure how I can properly validate emails, is there any other / working way?

Related

Send array via postman

I would like to send array of id's via postman
https://stackoverflow.com/questions/12756688/is-it-possible-to-send-an-array-with-the-postman-chrome-extension
I looked on to above thread, for me array[] /array[0] didn't work out,
using same key with different value worked for me.
It gave
But I am not able to send single element in array or an empty array.
I see it in req.body as a string of characters
So how should I send it?
So I just needed to set extended option of urlencoded to true and use arr[0] in postman, and it worked for me.
just make express.urlencoded({extended : true});
it was set to false before and arr[] or arr[0] didnot worked.

PasswordSignInAsync returning Success instead of RequiresVerification

I'm trying to set up Two Factor Authentication on our app. Updated a user in AspNetUsers table and set it's TwoFactorEnabled value to 1 for testing.
While debugging, signInManager.PasswordSignInAsync return just "success", not "requires verification".
This is the line
signInStatus = await signInManager.PasswordSignInAsync(viewModel.Email, viewModel.Password, true, shouldLockout: false);
(Similar questions are generally answered as first value should be name instead of email but I don't think it's the issue. Login works correctly, for example if password is wrong it returns failure.)
I added the line below to Startup.Auth.cs too
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(10));
I'm still able to work with what I have like this (though I don't want to)
if (signInStatus == SignInStatus.Success && user.TwoFactorEnabled == true)
{
//rest of code to be written
}
but this feels too makeshift of a solution and feels prone to many future errors. I'd prefer using Identity but I can't at the moment because of this problem.
It is obvious I'm doing something wrong or missing something but I don't know what. Thanks in advance.
I found my solution by copying the SignInManager code directly into mine and stepping through it, you can learn more about that here: https://stackoverflow.com/a/52357870/550975
SignInManager return RequiresVerification if :
dbo.ASpnetUsers has for user set to true TwoFactorEnabled and EmailConfirmed and user
email should be confirmed, email not be empty or null.

Validation In Express-Validator

I am using express-validator for validation. I am using mongoose for database, it also has validation built in. I want to know which one should I use?
I also want to know if the validation in express-validator is parallel. Take this code for example:
req.checkBody('email', 'Invalid email').notEmpty().isEmail().isUnique();
req.checkBody('password', 'Invalid possword').notEmpty().len(8, 30);
req.checkBody('first_name', 'Invalid first_name').notEmpty().isAlpha();
req.checkBody('last_name', 'Invalid last_name').notEmpty().isAlpha();
req.checkBody('dateofbirth', 'Invalid dateofbirth').notEmpty.isDate();
isUnique() is a custom validation method that checks if the email has not already been registered or not, it queries to database to validate so. Though not mentioned in the code above but I also have few other post request where I need to validate multiple fields where database queries will be made in each of them.
So I wanted to know if its possible to run each of the above check method in parallel as that would make it faster and would also me more node like. I obviously will like to use a module for running these in parallel like async. I would also like to know if already these check methods are running in parallel already?
Please help me figure this out? Thanks in advance.
express-validator is meant to validate input passed by the browser/client; Mongoose's validation is meant to validate newly created documents. Both serve a different purpose, so there isn't a clean-cut answer to which one you should use; you could use both, even.
As for the order of validation: the checks will be performed in series. You could use async.parallel() to make it appear as if the checks are performed in parallel, but in reality they won't be since the checks are synchronous.
EDIT: node-validator (and therefore express-validator) is a string validator. Testing for uniqueness isn't a string operation but operates on your data model, so you shouldn't try to use node-validator for it (in fact, I don't even think you can).
Instead, I would suggest using Mongoose's unique feature to ensure that an e-mail address only occurs once in your database.
Alternatively, use a validator module that supports async operations, like async-validate.
Using both mongodb unique constraint and express-validator will cause a little bit complicated errors processing: you need to analyse errors in different places and translate it to common format for rest response.
So another approach will be creating custom express validator which will find record with such value in mongodb:
router.use(expressValidator({
customValidators: {
isUsernameAvailable(username) {
return new Promise((resolve, reject) => {
User.findOne({ username: username }, (err, user) => {
if (err) throw err;
if(user == null) {
resolve();
} else {
reject();
}
});
});
}
}
})
);
...
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('username', 'Username already in use').isUsernameAvailable();
req.asyncValidationErrors().then(() => {
...
If you need, see total example with this code on my website: https://maketips.net/tip/161/validate-username-available-using-express-validator
Conclusion: express-validator supports asynchronous validation as well so you can perform any data and string validation you need without mixing user validation and low-level db backend validation
There is no way that Express-Validator can check a email address is unique or not, on the other hand MongoDB is not responsible for checking your entered email address is in correct format.
So you must have to use both of them when they are in need because they serve completly diffrent purpose.

ResolvePrincipal vs SearchPrincipal

So I'm attempting to write something to mimic sharepoint's people picker. I was originally using Utility.ResolvePrincipal with some success, but it was only returning me a single user (obviously). So, I tried to use Utility.SearchPrincipal. Only that's not returning me anything. Here's what I have:
var user = Utility.ResolvePrincipal(_clientContext, _clientContext.Web, nameStart, PrincipalType.user, PrincipalSource.All, null, false);
var users = Utility.SearchPrincipals(_clientContext, _clientContext.Web, nameStart, PrincipalType.user, PrincipalSource.All, null, 10);
_clientContext.ExecuteQuery();
At this point, user.Value has a single user, and users is an empty list. What am I doing wrong?
I eventually solved the issue by changing the PrincipalSource.All call in Utility.SearchPrincipals to just PrincipalSource.UserInfoList. Apparently it was running into some security issue in one of the sets of users, and instead of throwing an error it was just returning an empty list.

drupal_add_js() only adds the JS when no error message (D6)

In my custom form (in a custom module) drupal_add_js() only adds the JS when there is no error message.
My code goes like this:
function ntcf_redo_order_form( &$form_state = array() ) {
global $base_path, $user;
$my_dir = drupal_get_path('module', 'ntcf_redo');
drupal_add_js("$my_dir/order.js", 'module', 'header', FALSE, TRUE, FALSE);
$form = array();
...
return $form;
}
If the validation function used _form_set_error()_ to display an error message and highlight the offending field, the message is displayed and the field highlighted, but the _drupal_add_js()_ call does nothing. Without a pending error message to display, all is well.
EDIT: this problem does not occur with drupal_set_message(), only with form_set_error().
I tried adding the 3 later parameters to the *drupal_add_js()* call to tell it to not optimize it (don't combine it with other JS files). There is no mention of the file order.js in the HTML, and it makes no difference whether I use the last 4 parameters ('header', FALSE, TRUE, FALSE) or not.
In Admin/Performance, I turned off Optimize Javascript Files, and pretty much all caching, which also made no difference.
Extra Details:
I'm not sure if this makes a difference, but it wouldn't surprise me, so here goes:
What I'm doing here is a multi-part "wizard" form that allows the user to proceed forward and go back. Also, many of the pages use AJAX, so I need to do all the "required" field validation in the _submit function instead of letting Drupal do it automatically (since that makes a mess of AJAX). So, if there's a "required" field that's missing, the _submit() function sets an error message, and the form generation function generates the same form again (with the additional decoration resulting from the error message).
Also: this is off-topic, but it might help someone using Google: when doing a multi-page form that allows going backward, you MUST assign a weight to every item on the form, or else the fields tend to "wander" when you go backwards.
Any ideas?
I had the same problem, this is a workaround I found (for Drupal 7, may work in 6) :
1. in your form setup (or hook_form_alter), do this :
$form['#post_render'][]='yourfunction';
2. define :
function yourfunction($content,$element){
$my_dir = drupal_get_path('module', 'ntcf_redo');
drupal_add_js("$my_dir/order.js", 'module', 'header', FALSE, TRUE, FALSE);
return $content;
}
I think this works (while your approach does not), because hook_form_alter (and/or hook_form)
do NOT get called again for a prepared/cached form, so the initial form load WILL load the javascript, but subsequent posts will NOT.
HTH
Mikes answer ($form['#post_render'][]='yourfunction';), will work, though its not the optimal way and will cause issues with drupal_add_js.
The best way to do this is by adding your javascript via the form api '#attached'.
Instead of using drupal_add_js or a new callback on the '#post_render':
$form['#attached']['js'] = array(
drupal_get_path('module', 'module_name') .'/file/path/filename.js',
);
You may pass in a 'css' array as well. Being an array, you can pass in as may files as you want.
*This is for Drupal 7. Other versions may be different.

Resources