.NET/.NET Core instantly check whether a record already exists

In many cases, we need to check whether the input(username, phone number, etc.) that users type in already exists in database. In .NET/.NET Core, we can use DataAnnotation(or FluentAPI) to complete validations. In DataAnnotation, there’s a Remote() method which can help us to reach the “instant validation” purpose.

References

Steps

  1. Let’s say we have a UserSignUpViewModel, this model has an attribute called Username.
    public class UserSignUpViewModel {
    
        [Required(ErrorMessage = "请填写用户名")]
        [DisplayName("用户名")]
        [StringLength(20, MinimumLength = 2, ErrorMessage = "用户名长度在2-20位之间")]
        public string Username { get; set; }
    
        //...other attr....
    }

    Now we need to know whether it already exists in our database.

  2. First thing we nend to do is open the controller file and add a validate action.
    public JsonResult UsernameValidationJsonResult(string username)
    {
        bool isExists = db.Users.Any(x => x.Username == username);
        return Json(!isExists);
    }

    The return type is JsonResult though the return value will be just a “ture” or “false”.

    Note that if the username already exists, we need to return “false” to make the whole validation works.

  3. Then return to the model file, add Remote() DataAnnotation before the username attribute. Now the username section should be like this:
    public class UserSignUpViewModel {
        [Required(ErrorMessage = "请填写用户名")]
        [DisplayName("用户名")]
        [StringLength(20, MinimumLength = 2, ErrorMessage = "用户名长度在2-20位之间")]
        [Remote("UsernameValidationJsonResult", "Login", ErrorMessage = "用户名已存在")]
        public string Username { get; set; }
                
                //...other attrs...
    }

    The Remote() validation method needs two parameters——the action name in controller and the controller name.

  4. Open the View file which contains the username form, add JQuery script files that Visual Studio prepared for us.
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

    Then add the @Html.ValidationMessageFor() method in the form.

  5. It should work.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据