Use express validator and custom validation on field node js

523 views Asked by At

I am using express validator for validation. I wanted to check if the name is not empty and if it exists then remove the extra spaces between the string.

Using this below code only the second part of the validation works

  case 'name': {
  return [
    check('name', 'Name is required').not().isEmpty().trim().escape()
    .matches(/^[A-Za-z\s]+$/).withMessage('Name must be alphabetic.')
  
  ],(req,res,next) => {
    req.body.name = req.body.name.replace(/\s+/g, ' ');
    next();
  }
}

The above code gives this response which I don't want

//input
john    name  one 12

//output 
// it should give error Name must be alphabetic
john name one 12

How I achieve this using express validation and custom validation

0

There are 0 answers