Answer the question
In order to leave comments, you need to log in
Nodejs + express + mongoose - how to implement custom form validation?
I decided to look at the node. All sorts of rakes of misunderstanding have so far managed to be solved, but here it stalled.
Form validation is performed by means of express-form. When adding a new entry, it is necessary to check the existence in the database (mongodb/mongoose) of an entry with the same name. To do this, use a custom validator:
form.validate("name").custom(programExistsValidator)
const programExistsValidator = function (programName) {
ImageProgram.findOne({name: programName}, function (err, data) {
throw new Error("Программа с таким именем уже существует");
});
};
Answer the question
In order to leave comments, you need to log in
So, got it.
Ambush in the package description:
Which leads us to outdated documentation. The dandean/express-form project is currently closed. However, it was forked and supported by freewil/express-form. There is also more up-to-date documentation, in which there is such an example:
// Asynchronous custom validator (3 argument function signature)
form.field('username').custom(function(value, source, callback) {
username.check(value, function(err) {
if (err) return callback(new Error('Invalid %s'));
callback(null);
});
});
const programExistsValidator = function (programName, source, callback) {
ImageProgram.findOne({name: programName}, function(err, data){
if(err){
return callback(new Error('Ошибка проверки названия. Ошибка БД.'))
}
if(data !== null){
return callback(new Error('Программа с таким именем уже существует.'));
}
callback(null);
});
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question