Saturday 9 February 2013

Check email duplicacy with custom validator in asp.net

When we work on sign up page, mostly we need to check whether entered email id is duplicate in database. Either it can be achieved by server side or client side javascript/jQuery. We can use asp.net CustomValidator easily for this purpose. Below I have given controls and javascript function that is used for Validation.

JavaScript:

<script language="javascript" type="text/javascript">
    function CheckName(sender, args) {
        var txt = document.getElementById('<%=txtName.ClientID %>').value;
var count=  getDataFromDatabaseThroughWebServiceOrJavaScript(txt);
         if (count >0) {
     //if Email is already available
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }  
   
    }
</script>

ASPX Page:

<asp:TextBox runat="server" ID="txtName" ValidationGroup="checkEmail"></asp:TextBox>

<asp:CustomValidator ID="cstVal" runat="server" ValidationGroup="checkEmail"
        ValidateEmptyText="true" Display="Dynamic" ControlToValidate="txtName" 
        ErrorMessage="Email is available already!" ClientValidationFunction="CheckName" EnableClientScript="true" ></asp:CustomValidator>

<asp:Button ID="btnSubmit" runat="server" ValidationGroup="checkEmail" />

 In CustomValidation control,  ClientValidationFunction property should to be set to Java Script function name, like in this example CheckName is ClientValidationFunction. And  EnableClientScript should be set to True.

1 comment: