0

Using ASP.NET MVC.. I can do a server-side check to see if the email address that the user has submitted already exists in my database by doing this:

if (db.TableName.Any(x => x.Email.Equals(object.Email, StringComparison.CurrentCultureIgnoreCase) && x.ID != object.ID))
{
    ModelState.AddModelError("Email", "This email already exists!");
    return View(object);
}

If this was true, then I could return the model to the view and the email field would be highlighted red with the validation message below it.

But as of now I am using an api controller and calling that controller method via ajax.

var settings = {};
settings.baseUri = '@Request.ApplicationPath';
var infoGetUrl = "";
if (settings.baseUri === "/ProjectName") {
    infoGetUrl = settings.baseUri + "/api/controllername/";
} else {
    infoGetUrl = settings.baseUri + "api/controllername/";
}

$("#Create-Btn").on("click",
    function (e) {

        $("form").validate({
            submitHandler: function () {

                e.preventDefault();

                $.ajax({
                    method: "POST",
                    url: infoGetUrl,
                    data: $("form").serialize(),
                    success: function (data) {
                        toastr.options = {
                            onHidden: function () {
                                window.location.href = newUrl;
                            },
                            timeOut: 3000
                        }
                        toastr.success("Successfully created.");
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var status = capitalizeFirstLetter(textStatus);
                        var error = $.parseJSON(jqXHR.responseText);
                        toastr.error(status + " - " + error.exceptionMessage);
                    }
                });
            }
        });
    });

In my api controller post method I have this:

if (
    db.TableName.Any(
        x => x.Email.ToUpper().Equals(object.Email.ToUpper())))
{
    throw new Exception("This email already exists!"); 
}

Now, this does return the exception message within the toastr notification, but the email textbox is not highlighted red because it is not getting the bootstrap input-validation-error class added to it.

So my question is, is there a way to add a method to check the database to see if the email that the user is entering in the form already exists via jquery validation?

Any help is appreciated.

Grizzly
  • 5,873
  • 8
  • 56
  • 109

1 Answers1

1

You need to add something like this:

$("#formId").validate({
        rules:{email:{required:true,remote:"your api"}},
        messages:{email:"Correct email is required."},
        submitHandler:function(){
            alert("Correct email!");
        },
        success:function(label){
            label.addClass("valid").text("Valid email!")
        },
        onkeyup:false
    });
funcoding
  • 741
  • 6
  • 11
  • In case it isn't clear, this uses jQuery Validation's `remote` method. You can find more information at https://jqueryvalidation.org/remote-method/ if you need it. – Chris Pratt May 10 '17 at 13:20