Are there any Mongoose validation libraries? - javascript

I am new to mongoDB and mongoose in fact I am new to Javascript as a whole. As a result of this I'm not sure of how I should go about sanitizing my data.
I was wondering if there are any libraries with custom validation functions that take care of at least some generic dangers one should watch out for. Also it would be nice if it already had commonly used validation such as email, or character length.

Hi there are many libraries for mongoose schema validation.some of are listed below.
https://github.com/leepowellcouk/mongoose-validator,
https://github.com/SamVerschueren/node-mongoose-validator
both are good library for mongoose validation..Also mongoose provide custom logic for validation.
More if you want to create custom logic then https://github.com/chriso/validator.js helpful to you.
for email validation i use this
const emailRegex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/
email: {
type: String,
trim: true,
unique: true,
required: 'Email address is required',
validate: {
validator: (email)=> {
return emailRegex.test(email)
},
message: '{VALUE} is not a valid email'
},
match: [emailRegex, 'Please fill a valid email address']
}

Related

mongodb not detecting unique value in my node js project

I'm working on mongodb with node js and I realized that even though I used the unique true property on unique fields in my project, I realized that it doesn't work, what is the reason?
my code is like this
const CourseSchema = new Schema({
name: {
type: String,
required : true,
unique:true
},
description: {
type: String,
required: true,
trim: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
i want to prevent this code from saving duplicate usernames.
Such a check if not directly possible with the mongoDB library. However it is supported out of the box if you use mongoosejs
It may be possible that you already have duplicate values in your document before defining this property Delete the messed data from the MongoDB collections,
or make sure that mongodb auto indexing is true
mongoose.connect('url', {
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
})
I tried many ways, but I realized that this problem is version-related.
I found the solution by updating the version, thank you for your solution support.

How to normalize the input email?

I was working with express-validator when i encountered that i used normalize email for validation of email while signing up so i stored the normalized email to server.
Validation code:
router.post(
"/signup",
[
check("name").not().isEmpty(),
check("email").normalizeEmail().isEmail(),
check("password").isLength({ min: 6, max: 15 }),
],
userController.signupUser
);
Input email: abc.123#mail.com
normalized email: abc123#gmail.com (storing in db)
Now the problem is when working on login the input email doesn't matches and shows invalid credentials.
You just need to pass options inside normalizeEmail ():
normalizeEmail ({"gmail_remove_dots": false "})
After researching and observing I noticed that the code which was used at the time of signing up can be used to normalize email at the time of login, I just had to add:
router.post("/login",[check('email').normalizeEmail()], userController.loginUser);
After adding the email was converting to normalized one and can be used directly from requests.
You cannot remove any . or _ since it's part of the user's e-mail.
Here and example of validating an email address

Sequelize: Change "validate" meta data of column

Is it possible to change the "validate" meta data of a column using a migration file? I tried the queryInterface.changeColumn method and it seems like it can only change the three meta data mentioned in the docs (defaultValue, allowNull, and type).
I've tried doing something like this inside the 'up' object of the migration file:
queryInterface.changeColumn(
'tableName',
'columnName',
{
validate: {
is: /new_regex_validation/
}
}
)
However, the above attempt did not work for me when I ran "sequelize db:migrate"
For simplicity's sake, I'll use a table definition to elaborate on my question:
I'm trying to change an already existing table like this:
var tableName = sequelize.define('tableName', {
columnName: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
is: /some_regex_validation/
}
}
})
into this using sequelize migration:
var tableName = sequelize.define('tableName', {
columnName: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
is: /a_new-or-different_regex_validation/
}
}
})
or simply remove the validate meta data while using sequelize migration:
var tableName = sequelize.define('tableName', {
columnName: {
type: DataTypes.STRING,
unique: true,
allowNull: false
}
})
Any ideas?
Validation happens on the client, not on the database. You don't need a migration for it.
I came across this question a few times trying to understand the difference between building my model with validations and using migrations.
I found this link very helpful. Hopefully someone else does in the future.
Difference between Validations and Constraints
Validations are checks performed in the Sequelize level, in pure
JavaScript. They can be arbitrarily complex if you provide a custom
validator function, or can be one of the built-in validators offered
by Sequelize. If a validation fails, no SQL query will be sent to the
database at all.
On the other hand, constraints are rules defined at SQL level. The
most basic example of constraint is an Unique Constraint. If a
constraint check fails, an error will be thrown by the database and
Sequelize will forward this error to JavaScript (in this example,
throwing a SequelizeUniqueConstraintError). Note that in this case,
the SQL query was performed, unlike the case for validations.
https://sequelize.org/master/manual/validations-and-constraints.html

backbone validate single attribute in save only

I have one model with 2 attributes. Let me explain first.
Backbone.Model.extend({
validation: {
username: [
{required: true, msg: 'Enter email/username.'},
],
password: [
{required: true,msg: 'Enter password.'},
{minLength:20,msg: 'Incorrect password length.'}]
},
});
I want validate single attribute in save function. Do you have any idea?
means, If my username & password field is blank, then error should be occurred for username only.
I am using backbone.validation with backbone.
Thanks
To validate a single or multiple properties, using Backbone.Validation, use the following code:
yourModel.isValid('username') // or
yourModel.isValid([ 'attribute1', 'attribute2' ])
There are two approaches you might use:
Approach 1
I think the easiest way to do this would be that you don't set the password field until after the username is validated. To quote from the FAQ:
What gets validated when?
If you are using Backbone v0.9.1 or later, all attributes in a model will be validated. However, if for instance name never has been set (either explicitly or with a default value) that attribute will not be validated before it gets set.
This is very useful when validating forms as they are populated, since you don't want to alert the user about errors in input not yet entered.
If you need to validate entire model (both attributes that has been set or not) you can call validate() or isValid(true) on the model.
So, don't call validate on your whole model. Call it on the username field first, then the password field.
Also, don't set the password field in your model until after the username has been validated.
Approach 2
Another approach would be to use the conditional validation described in the FAQ:
Do you support conditional validation?
Yes, well, sort of. You can have conditional validation by specifying the required validator as a function.
So, your code might look something like:
Backbone.Model.extend({
validation: {
username: [
{required: true, msg: 'Enter email/username.'},
],
password: [
{required: function(val, attr, username) {
return Bool(username); //some code here- return true if username is set, false if it is not. This rough example may not work in the real world.
},msg: 'Enter password.'},
{minLength:20,msg: 'Incorrect password length.'}]
},
});
I'm pretty sure that's what Ulugbek Komilovich is suggesting, though I'm not sure the syntax in that answer is quite correct.
M = Backbone.Model.extend({
validation: {
username: [
{required: true, msg: 'Enter email/username.'},
],
password: function(value, attr, computedState) {
// new M(this.get('username')); //or use second way
if(this.get('username')) {
return 'Enter email/username.';
}
// other checks
}
},
});

Troubleshooting remote jquery plugin requests

I'm trying to use the remote option to check an email and see if the entered one is currently in the database. Using the Remember the Milk example on the site I have my js function set up as follows:
$(function() {
// validate signup form on keyup and submit
$("#registrationForm").validate({
rules: {
firstname: "required",
lastname: "required",
password: {
required: true,
minlength: 5
},
password_confirm: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true,
remote: "byob/processors/checkEmail.php"
}
}
});
});
However nothing is happening. I thought that perhaps I had the path to the file wrong, but looking under the Network tab in the Chrome Inspector.. no call is being made to the php file; I expect that one should be, and I should at least be getting a 404.
If this document would not show up that way, please advise on some methods to try troubleshooting this, since without getting a response from the server it is very difficult!
Seems to work just fine for me..
Keep in mind that the validation for existence will happen after it passes the required (must be non-empty) check and the valid email check..
Make sure the input is named correctly as well..
demo at http://jsfiddle.net/gaby/XFpcN/1/

Categories