Reputation: 539
I have two input text boxes which are decimal.
The sum of the two inputs cannot be more than 100. When input1 is 40, input2 cannot be more than 60.
I need to do everything in client side and need to allow client to enter any value. If the entered value is more than the limit, I need to show the validator error message:
Page.isValid = false
Now I have two separate validator for each input box but I don't know how to change the valueToCompare of two validators in client side.
Please advise,
Thanks
Upvotes: 0
Views: 647
Reputation: 78880
You should look into using the CustomValidator control. Here's an article that walks you through using it.
Your code could look something like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validateTextBoxen(sender, args) {
// You'll have more thorough validation, I'm sure
var value1 = parseFloat(
document.getElementById('<%=textBox1.ClientID%>').value);
var value2 = parseFloat(
document.getElementById('<%=textBox2.ClientID%>').value);
args.IsValid = (value1 + value2) < 100;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textBox1" runat="server" />
<asp:TextBox ID="textBox2" runat="server" />
<asp:CustomValidator runat="server" EnableClientScript="true"
OnServerValidate="onCustomValidation" ID="customValidator"
ErrorMessage="Invalid!"
SetFocusOnError="true" ClientValidationFunction="validateTextBoxen"/>
<asp:Button runat="server" OnClick="button_Click"/>
<asp:Literal runat="server" ID="placeholder" />
</div>
</form>
</body>
</html>
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void onCustomValidation(
object sender, ServerValidateEventArgs e)
{
float value1 = 0f;
float value2 = 0f;
if (!float.TryParse(textBox1.Text, out value1)
|| !float.TryParse(textBox2.Text, out value2)
|| value1 + value2 > 100f)
{
e.IsValid = false;
}
}
protected void button_Click(object sender, EventArgs args)
{
placeholder.Text = Page.IsValid ? "Valid" : "Invalid";
}
}
}
Upvotes: 4
Reputation: 7297
On client side, on the click of button, use ClientClick property, and set it to javascript function name to validate the input
e.g.
<asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server" Text="Submit" ></asp:Button>
And write a validate() function in javascript, which check the sum of both inputs
Upvotes: 0
Reputation: 180858
Nowadays the best way to validate HTML forms IMO is with a jQuery plugin like this one.
Upvotes: 0