How to use the escape function from validator

Find comprehensive JavaScript validator.escape code examples handpicked from public code repositorys.

85
86
87
88
89
90
91
92
93

exports.show = show;

var create = function (req, res, next) {
  var title = validator.trim(req.body.title);
  title = validator.escape(title);
  var tab = validator.trim(req.body.tab);
  tab = validator.escape(tab);
  var content = validator.trim(req.body.content);
fork icon0
star icon72
watch icon8

+ 3 other calls in file

239
240
241
242
243
244
245
246
247
248
		const username = await user.getUserField(postData.uid, 'username');
		const translated = await translator.translate(`[[modules:composer.user_said, ${username}]]`);
		return `${translated}\n` +
			`> ${postData ? `${postData.content.replace(/\n/g, '\n> ')}\n\n` : ''}`;
	} else if (req.query.body || req.query.content) {
		return validator.escape(String(req.query.body || req.query.content));
	}
	return postData ? postData.content : '';
}

fork icon53
star icon12
watch icon12

+ 5 other calls in file

11
12
13
14
15
16
17
18
19
20

const version = '1.0.3'

router.post('/', (req, res, next) => {
  const imagedata = req.body.image
  const country_code = (req.body.country_code) ? validator.escape(req.body.country_code) : 'eu'
  const pattern_code = (req.body.pattern_code) ? '-p ' + validator.escape(req.body.pattern_code) : ''

  /* Validate input */
  if (!imagedata || validator.isBase64(imagedata)) {
fork icon6
star icon4
watch icon2

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
24
for (key in refs.datasets)
{
	// extension
	if (refs.datasets[key].hasOwnProperty('extension'))
	{
		refs.datasets[key].extension = validator.escape(refs.datasets[key].extension);
		if (
			refs.datasets[key].extension.charAt(0) !== '.'
			|| refs.datasets[key].extension.length > 6
			|| !validator.isAlphanumeric(validator.ltrim(refs.datasets[key].extension, '.'))
fork icon5
star icon20
watch icon0

7
8
9
10
11
12
13
14
15
16
17
18
};


export const sanitizeToken = dirtyToken => validator.escape(dirtyToken);


export const sanitizeAndValidateName = dirtyName => {
    const sanitizedName = validator.escape(dirtyName);
    const isAlpha = validator.isAlpha(sanitizedName);
    return isAlpha ? sanitizedName : '';
};

fork icon0
star icon1
watch icon0

+ 3 other calls in file

68
69
70
71
72
73
74
75
76
77
        buildCategories(req.uid, searchOnly),
]);

searchData.pagination = pagination.create(page, searchData.pageCount, req.query);
searchData.multiplePages = searchData.pageCount > 1;
searchData.search_query = validator.escape(String(req.query.term || ''));
searchData.term = req.query.term;

if (searchOnly) {
        return res.json(searchData);
fork icon0
star icon1
watch icon1

312
313
314
315
316
317
318
319
320
321
postData.topic = results.topicInfo;
postData.index = parseInt(results.topicInfo.postcount, 10) - 1;

// Username override for guests, if enabled
if (parseInt(meta.config.allowGuestHandles, 10) === 1 && parseInt(postData.uid, 10) === 0 && data.handle) {
	postData.user.username = validator.escape(String(data.handle));
}

postData.votes = 0;
postData.bookmarked = false;
fork icon1
star icon0
watch icon0

135
136
137
138
139
140
141
142
143
144
}

db.parseIntFields(user, intFields, requestedFields);

if (user.hasOwnProperty('username')) {
	user.username = validator.escape(user.username ? user.username.toString() : '');
}

if (user.hasOwnProperty('email')) {
	user.email = validator.escape(user.email ? user.email.toString() : '');
fork icon1
star icon0
watch icon0

16
17
18
19
20
21
22
23
24
25
26


apiController.loadConfig = async function (req) {
	let config = {
		relative_path: nconf.get('relative_path'),
		upload_url: nconf.get('upload_url'),
		siteTitle: validator.escape(String(meta.config.title || meta.config.browserTitle || 'NodeBB')),
		browserTitle: validator.escape(String(meta.config.browserTitle || meta.config.title || 'NodeBB')),
		titleLayout: (meta.config.titleLayout || '{pageTitle} | {browserTitle}').replace(/{/g, '{').replace(/}/g, '}'),
		showSiteTitle: meta.config.showSiteTitle === 1,
		minimumTitleLength: meta.config.minimumTitleLength,
fork icon1
star icon0
watch icon0

+ 4 other calls in file

22
23
24
25
26
27
28
29
30
31
}
if (sanitization.trim) {
  sanitizefield = Validator.trim(sanitizefield);
}
if (sanitization.escape) {
  sanitizefield = Validator.escape(sanitizefield);
}
if (sanitization.unescape) {
  sanitizefield = Validator.unescape(sanitizefield);
}
fork icon0
star icon3
watch icon0

11
12
13
14
15
16
17
18
19
20
21
let sockets = [];
server.on('connection', function(socket) {
  sockets.push(socket);


  socket.on('message', function(msg) {
    let message = validator.escape(msg.toString('utf-8'));
    console.log('SOCKET Received : ', message);
    result = message.split('  ');
    checkPassword(result[0], (auth) => {
      let userId = validator.toInt(result[1]);
fork icon0
star icon2
watch icon0

69
70
71
72
73
74
75
76
77
78
db.parseIntFields(group, intFields, fields);

escapeGroupData(group);
group.userTitleEnabled = ([null, undefined].includes(group.userTitleEnabled)) ? 1 : group.userTitleEnabled;
group.labelColor = validator.escape(String(group.labelColor || '#000000'));
group.textColor = validator.escape(String(group.textColor || '#ffffff'));
group.icon = validator.escape(String(group.icon || ''));
group.createtimeISO = utils.toISOString(group.createtime);
group.private = ([null, undefined].includes(group.private)) ? 1 : group.private;
group.memberPostCids = group.memberPostCids || '';
fork icon1
star icon0
watch icon5

+ 41 other calls in file

418
419
420
421
422
423
424
425
426
427
if (type === 'default') {
    picture = '';
} else if (type === 'uploaded') {
    picture = await user.getUserField(data.uid, 'uploadedpicture');
} else if (type === 'external' && url) {
    picture = validator.escape(url);
} else {
    const returnData = await plugins.hooks.fire('filter:user.getPicture', {
        uid: caller.uid,
        type: type,
fork icon1
star icon0
watch icon5

+ 13 other calls in file

240
241
242
243
244
245
246
247
248
249
250
251
    return lastrestart;
}


async function getPopularSearches() {
    const searches = await db.getSortedSetRevRangeWithScores('searches:all', 0, 9);
    return searches.map(s => ({ value: validator.escape(String(s.value)), score: s.score }));
}


dashboardController.getLogins = async (req, res) => {
    let stats = await getStats();
fork icon1
star icon0
watch icon5

+ 21 other calls in file

111
112
113
114
115
116
117
118
119
120
await addUserData(eventsData, 'uid', 'user');
await addUserData(eventsData, 'targetUid', 'targetUser');
eventsData.forEach((event) => {
    Object.keys(event).forEach((key) => {
        if (typeof event[key] === 'string') {
            event[key] = validator.escape(String(event[key] || ''));
        }
    });
    const e = utils.merge(event);
    e.eid = undefined;
fork icon1
star icon0
watch icon5

+ 9 other calls in file

85
86
87
88
89
90
91
92
93
94
    await events.log({
        type: 'topic-rename',
        uid: caller.uid,
        ip: caller.ip,
        tid: editResult.topic.tid,
        oldTitle: validator.escape(String(editResult.topic.oldTitle)),
        newTitle: validator.escape(String(editResult.topic.title)),
    });
}
const postObj = await posts.getPostSummaryByPids([editResult.post.pid], caller.uid, {});
fork icon1
star icon0
watch icon5

142
143
144
145
146
147
148
149
150
151
        postObj.replies = replies[i];
        postObj.selfPost = parseInt(uid, 10) > 0 && parseInt(uid, 10) === postObj.uid;

        // Username override for guests, if enabled
        if (meta.config.allowGuestHandles && postObj.uid === 0 && postObj.handle) {
            postObj.user.username = validator.escape(String(postObj.handle));
            postObj.user.displayname = postObj.user.username;
        }
    }
});
fork icon1
star icon0
watch icon5

290
291
292
293
294
295
296
297
298
299
Topics.getTagData = async function (tags) {
    if (!tags.length) {
        return [];
    }
    tags.forEach((tag) => {
        tag.valueEscaped = validator.escape(String(tag.value));
        tag.valueEncoded = encodeURIComponent(tag.valueEscaped);
        tag.class = tag.valueEscaped.replace(/\s/g, '-');
    });
    return tags;
fork icon0
star icon0
watch icon1

+ 6 other calls in file

124
125
126
127
128
129
130
131
132
133
function getLang(req, res) {
    let language = (res.locals.config && res.locals.config.userLang) || 'en-GB';
    if (res.locals.renderAdminHeader) {
        language = (res.locals.config && res.locals.config.acpLang) || 'en-GB';
    }
    return req.query.lang ? validator.escape(String(req.query.lang)) : language;
}

async function translate(str, language) {
    const translated = await translator.translate(str, language);
fork icon0
star icon0
watch icon1

+ 5 other calls in file

587
588
589
590
591
592
593
594
595
596
});

describe('Title escaping', () => {
    it('should properly escape topic title', (done) => {
        const title = '"<script>alert(\'ok1\');</script> new topic test';
        const titleEscaped = validator.escape(title);

        const topicPostData = { uid: topic.userId, title: title, content: topic.content, cid: topic.categoryId };
        topics.post(topicPostData, (err, result) => {
            assert.ifError(err);
fork icon0
star icon0
watch icon1

+ 5 other calls in file