简体   繁体   中英

getting isEmail of undefined error when creating registration system in nodejs

Sorry I'm new to javascript and nodejs, but basically I am trying to create a registration system. I've attached my form validator and my user schema, but I keep getting an isEmail of undefined error. I'm not sure if there's an easier way to go about checking these conditions. Earlier, I was using req.checkBody, but I wasn't sure how to use that to check if a certain user is above a given age.

  router.post('/register', function(req, res, next) {
  var name = req.body.name; 
  var email = req.body.email;
  var password = req.body.password; 
  var password2 = req.body.password2; 
  var bday = req.body.bday; 
  var birthday = moment(bday); 
  let errors = []; 

  // Form Validator
  if (!name || !email || !password || !password2 || !bday) {
    errors.push({ msg: 'Please fill in all required fields' }); 
  }

  if (!req.body.email.isEmail()) {
    errors.push({ msg: 'Please provide an appropriate email' }); 
  }  

  if (req.body.password2 != req.body.password) {
    errors.push({ msg: 'Please make sure your passwords match' }); 
  }

  if (!birthday.isValid()) {
    errors.push({ msg: 'Date of Birth must be in appropriate format' }); 
  }

  if (moment().diff(birthday, 'years') < 13) {
    errors.push({ msg: 'User must be at least 13 years of age' }); 
  }
    if(errors.length > 0){
    res.render('register', {
      errors, 
      name, 
      email, 
      password, 
      password2, 
      bday
    });
  } else{
    var newUser = new User({
      name: name,
      email: email,
      password: password,
      bday: bday, 
    });


var UserSchema = mongoose.Schema({
    password: {
        type: String
    },
    email: {
        type: String
    },
    name: {
        type: String
    },
    bday: {
        type: String
    }
});

When you look at this here

  if (!req.body.email.isEmail()) {
    errors.push({ msg: 'Please provide an appropriate email' }); 
  }

You are trying to access the isEmail properties from email which must've been non existent.

What the req might have looked like: { req: { body: {} } } , as you can see email must be undefined and undefined does not contain isEmail property.

What you can do is

  if (req.body.email && !req.body.email.isEmail()) {
    errors.push({ msg: 'Please provide an appropriate email' }); 
  }

Check first if req.body.email exists before trying to access isEmail .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM