Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
how to validate an input from the front end , in the backend - MERN

I have created a react app to take user inputs.

class VehiReg extends Component {
    constructor(props){
        super(props);
        this.state={
            vehicle:"",
            plateNo:"",
            owner:"",
            manufacturer:"",
            manufacturedYear:"",
            color:""
        }
    }


    takInput = (e) => {
        const {name,value}= e.target;
        this.setState({
            ...this.state,
            [name]:value
        })
    }

    register = (e) =>{
        e.preventDefault();
        const {plateNo,owner,manufacturer,manufacturedYear,color,vehicle} = this.state;
        const data ={
            plateNo:plateNo,
            owner:owner,
            manufacturer:manufacturer,
            manufacturedYear:manufacturedYear,
            color:color,
            vehicle:vehicle
        }
        console.log(data);
        axios.post("http://localhost:8080/registrations/new",data).then((res)=>{
            if(res.data.success){
                  this.setState({
                      vehicle:"",
                      plateNo:"",
                      owner:"",
                      manufacturer:"",
                      manufacturedYear:"",
                      color:""
                  })
            }
        })
    }

 <div className="box">
                            <input placeholder="Enter the licence plate number "
                                   className="input2" name="plateNo" value={this.state.plateNo} onChange={this.takInput} />
                        </div>

then I want to validate the input which the user enters. The vehicle license plate can be in many forms:

· Vintage: 13 ශ්‍රී 9999

· Old: 250-9999, 19-9999

· Modern: WP GA-9999, CAR-9999

then according to the type which the user enters I want to write a function in the backend to validate and categorize the user inputs. Then again I want to return the vehicle type to the frontend

the main thing that I want to know is how can I validate the user input in the backend. here is the code I have written for entering the data into the database, before entering the data into the database that validation function should be executed.

//new registration
router.post("/registrations/new",(req, res)=>{
    let newRegistration = new Registrations(req.body);
    newRegistration.save((err)=>{
        if(err){
            return res.status(400).json({
                error:err
            })
        }
        return res.status(200).json({
            success:"registration Ok"
        });
    });
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are different types of doing validations and I will share one which I have used hope this can help you.

In Frontend: add properties to state:

    this.state = {
    plateNo: '',
    plateNoError: ''},
    plateNoValid: false,
  }
 
 takInput = (e) => {
    const {plateNo,value}= e.target;
    const plateNoRegEx =
               `^[A-Z]{2}[ -][0-9]{1,2}(?: [A-Z])?(?: [A-Z]*)? [0-9]{4}$`
    if(!value){
        this.setState({
        ...this.state,
        [plateNoError]:"Plate number cannot be empty"
      })
    }else if(!plateNo.match(plateNoRegEx)){
       this.setState({
           ...this.state,
           [plateNoError]:"Invalid Plate Number"
        })
   }else{
      this.setState({
           ...this.state,
           [plateNo]: value,
           [plateNoError]:''
        })
   }
}

 <div className="box">
           <input placeholder="Enter the licence plate number "
             className="input2" name="plateNo" value= 
              {this.state.plateNo} onChange={this.takInput} />
           {this.state.plateNoError && 
             <p>{this.state.plateNoError}</p>
           }
 </div>

For backend you can use 1)Express validator - npm install --save express-validator 2)Joi - https://joi.dev/ - npm i joi

both are good for validating requests and you can follow the (route - controller -service) format, where you can write validations in route.

eg: router
    .route('/registrations/new')
    .post(validate(publicValidation.getUserByEmail), 
                      publicController.getUserByEmail)

    const getUserByEmail = {
    body: Joi.object().keys({
        email: Joi.string().required(),
        .....
    })
   };
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda