Membuat validasi
static validation(title, bandName){
const errors = []
if(!title){
errors.push(`Title is required.`)
}
if(!bandName){
errors.push(`Band name is required.`)
}
return errors;
}
Javascript Validator is easy to use tool to validate JavaScript code. Copy, Paste and
Validate JavaScript. This JS linter checks the js code and highlights errors as well
as shows the detail of the error in a plain and easy-to-read gradient table.
didalam add masukkan ini
static createSong(title, bandName, duration, genre, createDate, lyric, imageUrl, LabelId, cb) {
const errors = SongModel.validation(title, bandName)
if(errors.length){
cb({
code: 1,
errors
})
}else{
let queryInsertSong = `
insert into "Songs" ("title", "bandName", "duration", "genre", "createdDate", "lyric", "imageUrl", "totalVote", "LabelId")
values ('${title}', '${bandName}', ${duration}, '${genre}', '${createDate}', '${lyric}', '${imageUrl}', 0, ${LabelId});`
pool.query(queryInsertSong, (err) => {
if (err) {
cb({
code: 2,
err
})
} else {
cb(null)
}
})
}
}
JS Validator uses JavaScript libs for validating and presenting warnings and errors.
It process and validates js in a browser environment. Just Paste your JS code and
click Validate JS. This tool does not send js code to the server for validating.
In the case of js file upload, Browser reads the file and for URL upload,
it sends the javascript URL to server and return js data and then run the
validation logic
didalam controllers
static addReadSong(req, res){
const {errors} = req.query
LabelModel.viewLabel((err, data) => {
if(err){
res.send(err)
}else{
res.render('add-song', { data: data, errors })
}
})
}
static addSong(req, res){
const { title, bandName, duration, genre, createDate, lyric, imageUrl, LabelId } = req.body
// console.log(imageUrl, 'dari control');
SongModel.createSong(title, bandName, duration, genre, createDate, lyric, imageUrl, LabelId, (err) => {
if(err){
if(err.code === 1){
res.redirect(`/songs/add?errors=${err.errors}`)
}else{
res.send(err)
}
}else{
res.redirect('/songs')
}
})
}
didalam ejsnya
<% if(errors) { %>
<% errors.split(',').forEach(el => { %>
<b><p class="text-danger"><%= el %></p></b>
<% }) %>
<% } %>


No comments:
Post a Comment