How to use the textbox event

advertisements

I have a registration form and i want to do some thing like this: When user register and enter the username then check on database that this user is already in database or not.That's why when user enter username and move to another field then check it.

So please help me how to solve this and how use textbox events.


As you have not provided any markup i'm assuming the markup like this.

<form id="form1" action="~/something.aspx" method="post">
    <label>Username</label>:
    <input type="text" id="username" name="username" onblur="validate();"/>
    <br/>
    <label>Password:</label>
    <input type="text" id="password" name="password"/><br/>
    <input type="submit" value="submit"/>
</form>

The basic idea is that you need to write some javascript for username field when the focus is out(onblur event)

Here is the javascript for the above piece of code.

<script type="text/javascript">
function validate()
{
    //make an ajax call to retrieve the username
    $.ajax({
        url:'validate.aspx/ValidateUsername',
        dataType: 'json',
        //... make necessary adjustments in ajax call so as to
        //call the web method in validate.aspx page
        success: function(data){
            if(!data.d){
                alert('username already exists !');
                document.getElementById('username').focus();
            }
        }
    });
}
</script>

Now defined your webmethod for the ajax call defined.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ValidateUsername()
{
   //Now query the database to check if the username exists.
   //If the username exists return 'true' other wise return 'false'
}

Hope this helps.