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.