Home > OS >  Validation using golang, gin and gorm with postgres like email already exist in database
Validation using golang, gin and gorm with postgres like email already exist in database

Time:01-07

I have something like this and I would like to check if email already exist in DB:

func RegisterUser(c *gin) {
var user models.User
if err := c.ShouldBindJSON(&user); err != nil {
    c.JSON(http.StatusBadRequest, gin.H{
        "messAge": err.Error(),
        "data":    "",
    })
    return
}
// **I TRIED SOEMTHING LIKE THIS**
err := database.DB.Find(&user.Email).Error
if err != nil {
    c.JSON(401, gin.H{"MESSAGE": "Email ALREADY exist",
    return
}
// **but is not working, because ANY mail it give me error**


if !strings.Contains(user.Email, "@") {
    c.JSON(400, gin.H{"MESSAGE": utils.ErrEmailWrong})
    return
}

if len(user.Password) < 4 {
    c.JSON(400, gin.H{"MESSAGE": utils.ErrPasswordLength})
    return
}

database.DB.Create(&user)
c.JSON(200, gin.H{
    "MESSAGE": "CREATED",
})
}

With this code, every time is telling me that : Email already exist, only works for the first time.

CodePudding user response:

plase read the document: https://gorm.io/docs/query.html

var userFind models.User
database.DB.Where("email = ?", user.Email).First(&userFind)

CodePudding user response:

Since, your struct object is not a slice. You should use ErrRecordNotFound.

Note : ErrRecordNotFound only works with First, Last, Take which is expected to return some result. And RecordNotFound is removed in V2.

if err != nil {
     if errors.Is(err, gorm.ErrRecordNotFound){
           c.JSON(401, gin.H{"MESSAGE": "Email Not Found",
           return

     }
    c.JSON(401, gin.H{"MESSAGE": "Your Message",
    return
}

OR

If you want to avoid the ErrRecordNotFound error, you could use Find like db.Limit(1).Find(&user), the Find method accepts both struct and slice data. And check like this :

result.RowsAffected // returns count of records found

For better understanding refer the link here : https://gorm.io/docs/v2_release_note.html#ErrRecordNotFound and https://gorm.io/docs/query.html

And, If you want to add record in DB though email exist then you should remove unique constraint and also check the error while creating the record. If record successfully created then return success response else return the appropriate error message.

  •  Tags:  
  • Related