Validate if input already exist in database ASP .NET Core 2.2

2.5k views Asked by At

I have a form with some input fields and when you click on Save, I do a check if a field already exist in the database. I have a service method for this.

For example in the database the field with value "Test10" already exist and if the user use "Test10" in the input field and clicks on save I want to show this message :

enter image description here

private async Task<bool> CheckIfCodeAlreadyExist(string code)
{
    return await _service.CheckCodeExist(code);
}

I tried with session vaiables, with an extra bool parameter but not effective enough. My JavaScript knowlegde is not that much, but would it possible to check this with a "onClick" event in the form?

If the result is true you stay on the page with the message.

enter image description here

Don't mind the Model.Code is red.

2

There are 2 answers

7
Pirate On

You don't need to do it with onClick if you have liberty to use Remote validation .net MVC offers.

Decorate you model property with something like:
[Remote("Action", "Controller", ErrorMessage = "Invalid Code")]
Or pass additional fields as well:
[Remote("Action", "Controller", AdditionalFields = "Id", ErrorMessage = "Invalid Code")]

with javascript and jquery, you do ajax request.

Bind click event to button:

$('#button').on('click', function(){
  $.ajax({
     url: '/Controller/Action',
     method: 'get',
     data: {
        code: $('#Code').val()
     }
   }).done(function (result) {
      if (result) {
         // code valid
         $('form').submit();
      } else {
         // show error
      }
   }).fail(function () {
        // ajax request failed
   });
});

Controller/Action to return bool:

public async Task<bool> CheckIfCodeAlreadyExist(string code)
{
    return await _service.CheckCodeExist(code);
}
0
Adam On

Take a look at Microsoft's documentation for model validation, specifically remote validation. The use case and example for this is almost identical to yours:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#remote-attribute-1

The [Remote] attribute implements client-side validation that requires calling a method on the server to determine whether field input is valid. For example, the app may need to verify whether a user name is already in use.

In your case, you may use a model with a Code property like this one:

[Remote(action: "CheckCode", controller: "Home")]
public string Code { get; set; }

On the server under the corresponding controller, you can provide the endpoint needed to validate the code:

[AcceptVerbs("Get", "Post")]
public IActionResult CheckCode(string code)
{
    if (!yourService.VerifyCode(code))
    {
        return Json($"Code {code} is already in use.");
    }

    return Json(true);
}