1

I am developing a webform which currently has a trigger on the Text Change event:

protected void txtBox1_TextChanged(object sender, EventArgs e)
  {
     Validate();
  }

The problem I am having is that this only fires once a user has entered text into a box and focus is lost.

The specific scenario I am having problems is:

  • User enters text into textbox control.
  • User clicks/tabs out of textbox control.
  • Textbox trigger runs as expected, and shows validation errors on the control.
  • User then clicks/tabs back into textbox control, highlights the existing text and deletes.
  • Function needs to run here to reset the validation message once the text has changed.
  • Without leaving the control they update the text.
  • User clicks/tabs out of the control and text changed trigger runs again.
mason
  • 31,774
  • 10
  • 77
  • 121
Si Blight
  • 109
  • 1
  • 13
  • This is because the `change` event only fires on a textbox after it loses focus. You need to use one of the key events, either `keypress`, `keyup` or `keydown`. Exactly how you do this in webforms I don't know, though. – Rory McCrossan Nov 25 '14 at 20:28
  • You need to perform your validation on the client (not using the Code Behind). This will avoid a ton of round trips to the server, be faster for the user, lighter on server resources, and be a better programming practice. Only once the form is submitted should you perform server side validation. – mason Nov 25 '14 at 20:28
  • @mason Sometimes you are forced to do a server side validation if the data is sensitive, we don't know if OP has something similar in his requirements. – Rex Nov 25 '14 at 20:31
  • @Rex You mean the validation itself is sensitive? I've never heard of that. Standard is to 1) perform client side validation as a convenience for the user and 2) perform server side validation in case the user skirted client side validation (ex, used the JS console or had JS disabled). – mason Nov 25 '14 at 20:32
  • @mason my validation function runs at server level to perform a series of database checks. If the user fails the validation my client would like when they start editing the field again, for the validation errors to be cleared, ready for the next time the validation triggers on focus loss. – Si Blight Nov 25 '14 at 20:41
  • If your validation involves calls to the database, I suggest you use [AJAX](http://en.wikipedia.org/wiki/Ajax_(programming)) to communicate with [Web API](http://www.asp.net/web-api) which will then check the database and return the results. Have the trigger be a client side event, such as one of those ones Rory recommended above. Code behind is a horrible place to do this, because you'll have to reload the entire page each time to make a check (ignoring UpdatePanel controls, which come with their own set of problems). – mason Nov 25 '14 at 20:45
  • possible duplicate of [Keep Focus back to the previous Textbox on failed validation](http://stackoverflow.com/questions/22403979/keep-focus-back-to-the-previous-textbox-on-failed-validation) – Paul Zahra Jan 21 '15 at 14:03

1 Answers1

0

This goes on your .aspx page:

<asp:TextBox runat="server" ClientIdMode="static" id="txtBox1">

<script type="text/javascript">
$("#txtBox1").on('input propertychange paste', function(){
    $.ajax({
        type: "POST",
        url: "api/MyValidator/ValidateTextBox?text=" + $("#txtBox1").val()
    }) //close AJAX call
    .done(function (resp){
        if(!resp.Valid) {alert('Not valid: ' + resp.msg);}
    }); //close Done handler
}); //close change handler
</script>

Here's the Web API function that will check the database and reply to the AJAX request.

public ValidationResponse ValidateTextBox(string text)
{
    //check your database. If it's good, set valid to true, otherwise false. If not valid, then set reason to the reason why it's not valid.
    bool valid;
    string reason;

    //construct response
    var response = new ValidationResponse(){ Valid = valid, msg = reason};

    //return response
    return response;
}

Also, put this class somewhere:

public class ValidationResponse
{
    public bool Valid {get; set;}
    public string msg {get; set;}
}

We use the example provided by How to detect a textbox's content has changed to detect when the textbox value changes. When it changes we make an AJAX call with jQuery to our Web API, where we return a response indicating it passed or failed validation. Then we use client side code in the .done() to check the response from the Web API and show a validation failed message when it fails.

I know this looks like a lot of code to check a single text box. But with a little manipulation, you could have it validate the entire form with a single AJAX call and it wouldn't be much more code than what we have now.

Note, I purposefully omitted some of the basic Web API configuration, since that's a lot to discuss in a single answer. My intention here wasn't to give you a "plug and play" answer, but rather to show you how easy it can be with a good architecture once you've learned the basics of AJAX and Web API.

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121