Reputation: 105
I have one text box and button in asp.net like
<tr>
<td style="width: 100px">
<asp:Label ID="lbltime" runat="server" Text="Enter Time"></asp:Label>
</td>
<td style="width: 100px">
<asp:TextBox ID="Txttime" onkeypress="return isNumberKey(event)" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px" align="center">
<asp:Button ID="Btntime" runat="server" Text="Button" />
</td>
</tr>
Now I want to write JavaScript code to validate on my textbox which work when I click on button. Now I want to know how to call function of JavaScript in button and the function should do work like is button should send the text box value to the function and function should check the value to integer number only. And if not found should give the error message in the dialog box that "please enter value in integer only".
I'm trying the JavaScript like this:
function isNumberKey(textboxvalue)
{
evt=textboxvalue.text;
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
textboxvalue.text="Enter in Integer Only";
return false;
return true;
}
Upvotes: 1
Views: 11619
Reputation: 11
Can you not use like var control = $("#<%= txtMyControl.ClientID %>"); return control;
?? then do standard validation ??
Upvotes: 1
Reputation: 9129
Use an <asp:CustomValidator /> for this.
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="myTextbox"
ErrorMessage="Enter Integer only!"
OnServerValidate="ServerValidation"
OnClientValidate="isNumberKey"
runat="server"/>
Your validation function looks like this:
function isNumberKey(oSrc, args) {
{
evt=textboxvalue.text;
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
args.isValid = false;
args.IsValid = true;
}
If you just want to check the data type, you can use a CompareValidator:
<asp:CompareValidator id="CompareValidator1"
runat="server" ErrorMessage="Enter Integer only!" Operator="DataTypeCheck"
ControlToValidate="Txttime" Type="Integer" />
The validators check on the client side if JavaScript is available AND on server side. All JavaScript will be generated for you. On the server, you always have to check, whether your page is valid or not:
protected void OnButtonClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
... // do your work on the server
}
}
Upvotes: 1
Reputation: 13503
ASP.NET has built-in validation controls that are able to cope with things like this:
http://msdn.microsoft.com/en-us/library/aa479013.aspx
In addition, make sure you don't rely on client-side validation only - check for an integer on the server-side, and reject the input if it isn't an integer.
Upvotes: 2