Use a CustomValidator
which is the only validator that allows to omit the ControlToValidate
:
<asp:CustomValidator runat="server" ID="CustomValidator1"
Text="The sum must be 100"
ClientValidationFunction="clientValidate"
EnableClientScript="True"
Display="Static">
</asp:CustomValidator>
The ServerValidate
:
Protected Sub ServerValidation(source As Object, args As ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
Dim val1 As Decimal
Dim val2 As Decimal
Dim val3 As Decimal
Dim val4 As Decimal
Dim val5 As Decimal
If Decimal.TryParse(TextBox1.Text, val1) AndAlso _
Decimal.TryParse(TextBox2.Text, val2) AndAlso _
Decimal.TryParse(TextBox3.Text, val3) AndAlso _
Decimal.TryParse(TextBox4.Text, val4) AndAlso _
Decimal.TryParse(TextBox5.Text, val5) Then
args.IsValid = val1 + val2 + val3 + val4 + val5 = 100
Else
args.IsValid = False
End If
End Sub
You can also provide a client validation function. Therefore you need to find the references to the textboxes per javascript and then calculate the total value on clientside.
For example:
<script type="text/javascript" >
function clientValidate(source, arguments) {
var txt1 = document.getElementById('<%= TextBox1.ClientID %>');
var txt2 = document.getElementById('<%= TextBox2.ClientID %>');
var txt3 = document.getElementById('<%= TextBox3.ClientID %>');
var txt4 = document.getElementById('<%= TextBox4.ClientID %>');
var txt5 = document.getElementById('<%= TextBox5.ClientID %>');
if(txt1 != null && txt2 != null && txt3 != null && txt4 != null && txt5 != null && txt1.value != "" && !isNaN(txt1.value) && txt2.value != "" && !isNaN(txt2.value) && txt3.value != "" && !isNaN(txt3.value) && txt4.value != "" && !isNaN(txt4.value) && txt5.value != "" && !isNaN(txt5.value))
{
var num1 = parseFloat(txt1.value);
var num2 = parseFloat(txt2.value);
var num3 = parseFloat(txt3.value);
var num4 = parseFloat(txt4.value);
var num5 = parseFloat(txt5.value);
arguments.IsValid = num1 + num2 +num3 + num4 + num5 == 100;
}
else
arguments.IsValid = false;
}
</script>