1

Ok, I am a beginner and working on an ALREADY EXISTING ASP.Net MVC 5 web app.

Overview of WebApp: This web app is more like work press and dynamically creates different sort of widgets and functionalities as per the client demand. So multiple URL's hits this web app and they all are treated as a separate web site. All the widgets have their own url's. these Url's are linked into different clients and all that fun stuff.(HUMOR me on this).

Issue: Issue might be totally unrelated to what I explained above. How to correctly use Remote Validation attribute in ASP.Net MVC 5. Below is code snippet and issue. I just have one Email Id field and I want to apply Remote validation to it.

Model

public class ForgotPasswordMV
{
    [Display(Name = "Email"), Required]
    [Remote("IsEmailUnique", "Settings", ErrorMessage = "Somethin Wrong")]
    public string EmailId { get; set; }
}

Controller Function

Public JsonResult IsEmailUnique(string EmailId)
{
    var respObj = SecurityHelper.EmailCount(EmailId); // if count > 1 returns false
    return Json(respObj, JsonRequestBehavior.AllowGet);
}

View File

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<h2>Forgot Password</h2>

@using (@Html.BeginForm("ForgotPassword", "Security"))
{
    @Html.ValidationSummary(true, "Please fix below error")
    @Html.AntiForgeryToken()
    <div class="form-group">
        @Html.LabelFor(m => m.EmailId)
        @Html.TextBoxFor(m => m.EmailId, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.EmailId)
    </div>
    <button class="btn btn-primary">Continue</button>
}

So, for the FIRST TIME when user enters email id and if return type is false then ErrorMessage = "Somethin Wrong" gets displayed properly. But the problem starts from second time. Now everytime I type the letters in the email field to change it. On every keyboard click the IsEmailUnique function starts getting hit. I mean when I see the ERROR MESSAGE for the FIRST TIME after seeing the error message I now went to the UI text box and started giving some other email id but now for every letter I put the remote validation method is getting hit. Ideally it should happen when I am tap out of the text box or click on the sbumit button (the way it worked for the first time)

EDIT

INSPECT ELEMENT CODE FOR THE UI TEXTBOX

    <div class="form-group">
     <label for="EmailId">Email</label>
     <input class="form-control input-validation-error" data-val="true" data-val-remote="Something went wrong" data-val-remote-additionalfields="*.EmailId" data-val-remote-url="/Settings/IsEmailUnique" data-val-required="The Email field is required." id="EmailId" name="EmailId" type="text" value="" aria-required="true" aria-invalid="true" aria-describedby="EmailId-error">

<span class="field-validation-error" data-valmsg-for="EmailId" data-valmsg-replace="true"><span id="EmailId-error" class="">Something went wrong</span></span>
</div>

Further More During second attempt (after successfully seeing Remote validation error) when I try adding any letter in Email ID Field I am noticing that below chunk of code gets hit and then the validation method IsEmailUnique is getting hit.

   public class SimRoute : Route
    {
        /// <summary>
        /// Base c-tor, implementing the base class ctor
        /// </summary>
        public SimRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler) { }

        /// <summary>
        /// This is where the "magic" happens - this is where the subdomain is retrieved & inserted into route values, so it can be referenced at a later time
        /// 
        /// The rest of the functionality is being retained by running the call to the base class
        /// </summary>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData routeData = base.GetRouteData(httpContext);

            if (routeData != null)
            {
                string[] temp = httpContext.Request.Url.Host.Split('.');

                if (temp.Length > 0)
                {
                    routeData.Values.Add("subdomain", temp.First());
                }
            }

            return routeData;
        }
    }

CALL STACK

enter image description here

To be honest, I am not sure what this above code snippet does, but why this code is getting hit as soon as I type any letter in the EmailID text box, or this code is even remotely related to the issue. My original question is, why Remote validation is happening on every letter put in textbox. I have tried to put as many details as I can in the question. Please guide me.

2
  • 1
    Because that is the default behavior of jquery.validate.js - Its 'lazy' (meaning you can tab through controls without triggering validation but once a control has been first validated because the value has changed, validation this then performed on .keyup()) Commented Aug 3, 2017 at 22:01
  • @StephenMuecke: Thanks. :) Commented Aug 4, 2017 at 1:23

1 Answer 1

1

I would advise you to try removing the onkeypress event from the field/form like explained in the following q&a

ASP.NET Remote Validation only on blur?

Sign up to request clarification or add additional context in comments.

3 Comments

But that will be a work around. Why it's happening in the first place?
Oh I am sorry, you mean to say this is expected standard behaviour of Remote validation. And I need to explicitly take care of it? I am a beginner so I am don't know much.
yes, there are standard behaviors, and you should always read the spec and stuff like in MSDN on how things works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.