SHARE
TWEET

Untitled

a guest Apr 23rd, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // for now, we're mocking NewsletterSignup:
  2. function NewsletterSignup() {
  3. }
  4. NewsletterSignup.prototype.save = function(cb) {
  5.   cb();
  6. };
  7.  
  8. var VALID_EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
  9.  
  10. app.post('/newsletter', function(req, res) {
  11.   var name = req.body.name || '', email = req.body.email || '';
  12.  
  13.   // input validation
  14.   if (!email.match(VALID_EMAIL_REGEX)) {
  15.     if(req.xhr) return res.json({ error: 'Invalid email address. '});
  16.     req.session.flash = {
  17.       type: 'danger',
  18.       intro: 'Validation error!',
  19.       message: 'The email address you entered was not valid.'
  20.     };
  21.     return res.redirect(303, '/newsletter/archive');
  22.   }
  23.  
  24.   new NewsletterSignup({ name: name, email: email }).save(function(err){
  25.     if (err) {
  26.       // couldn't save to database
  27.       if(req.xhr) return res.json({ error: 'Database error.'});
  28.       req.session.flash = {
  29.         type: 'danger',
  30.         intro: 'Database error!',
  31.         message: 'There was a database error; please try again later.'
  32.       };
  33.       return res.redirect(303, '/newsletter/archive');
  34.     }
  35.  
  36.     if(req.xhr) return res.json({ success: true });
  37.     req.session.flash = {
  38.       type: 'success',
  39.       intro: 'Thank you!',
  40.       message: 'You have now been signed up to the newsletter.'
  41.     };
  42.     return res.redirect(303, '/newsletter/archive');
  43.   });
  44. });
  45. app.get('/newsletter/archive', function(req, res){
  46.   res.render('newsletter/archive');
  47. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top