<asp:TextBox ID="txtPostalCode" runat="server"/>
<asp:CustomValidator ID="cvPostalCode" runat="server" ControlToValidate="txtPostalCode"
ClientValidationFunction="ClientValidate" OnServerValidate="ServerValidate"
ValidationGroup="Save"Display="Dynamic">*</asp:CustomValidator>
Add Following Javascript for client side validation
<script language="javascript" type="text/javascript">
function ClientValidate(source, arguments) {var country = document.getElementById('<%= ddlCountry.ClientID%>').value;
var postcode = arguments.Value;
if (country == 'USNJ') {
if ((postcode >= 07000 && postcode <= 07999) || (postcode >= 08500 && postcode <= 08999))
arguments.IsValid = true;
else {
arguments.IsValid = false;
source.errormessage = 'Please enter postal code in specified range of (07000-07999, 08500-08999).';
}
}
else if (country == 'USNY') {
if ((postcode >= 10000 && postcode <= 10399) || (postcode >= 10900 && postcode <= 11999))
arguments.IsValid = true;
else {
arguments.IsValid = false;
source.errormessage = 'Please enter postal code in specified range of (10000-10399, 10900-11999).';
}
}
else {
arguments.IsValid = true;
}
}
</script>
As if in the case of clientside script fail to be executed we can create server function to handel such situation. Here is server code that will get executed if client side script will fail to be executed.
protected void ServerValidate(object source, ServerValidateEventArgs value)
{CustomValidator cv = (CustomValidator)source;
string country = ddlCountry.SelectedValue;
if (country == "USNJ")
{
if ((Convert.ToInt32(value.Value) >= 07000 && Convert.ToInt32(value.Value) <= 07999) || (Convert.ToInt32(value.Value) >= 08500 && Convert.ToInt32(value.Value) <= 08999))
value.IsValid = true;
else
{
value.IsValid = false;
cv.ErrorMessage = "Please enter postal code in specified range of (07000-07999, 08500-08999).";
}
}
else if (country == "USNY")
{
if ((Convert.ToInt32(value.Value) >= 10000 && Convert.ToInt32(value.Value) <= 10399) || (Convert.ToInt32(value.Value) >= 10900 && Convert.ToInt32(value.Value) <= 11999))
value.IsValid = true;
else
{
value.IsValid = false;
cv.ErrorMessage = "Please enter postal code in specified range of (10000-10399, 10900-11999).";
}
}
else
{
value.IsValid = true;
}
}
You can code validation according to your business rules and set “IsValid” property to false if punched data is not valid and at last one more thing to do is on form submition (on sauve/update or submit).
protected void btnSubmit_Click(object sender, EventArgs e)
{if (Page.IsValid)
{
//Do save/Update
}
else
{
ltError.Text =”OOPS..Page is not valid”;
}
}
No comments:
Post a Comment