How could i make a textbox that accepts only numeric values? [duplicate] - c#

This question already has answers here:
asp.net validation to make sure textbox has integer values
(12 answers)
Closed 8 years ago.
I want to make a textbox that allows only numeric values to be entered.
how to achieve this?

use RegularExpressionValidator
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Only Numbers allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>
How to allow only integers in a textbox?

In ASP.NET try this:
<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer"
ControlToValidate="TxtBox" ErrorMessage=Error" />

You could use the ASP.NET Regular Expression Validator and write a RegEx that only accepts numeric values.
If you want to intercept keystrokes, so that only numerical keys are entered, you'll have to use JavaScript (I wouldn't do that).

dear you can do this by jquery try this if you are using jquery
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});

try below code
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationGroup="VGrpSave" SetFocusOnError="false" Display="None" ErrorMessage="Only numeric values are allowed" ControlToValidate="txtID" ValidationExpression="\d*"></asp:RegularExpressionValidator>
<asp:Button ID="btnSubmit" runat="server" ValidationGroup="VGrpSave" Text="Submit"></asp:Button>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List" ShowMessageBox="True" ShowSummary="false" ValidationGroup="VGrpSave" />

Related

asp.net Textbox Textmode Number, allow numbers only

I would just like to know if there is a way in ASP.NET to allow only numbers in textboxes with textmode="number"
when I use this:
<asp:TextBox runat="server" TextMode="Number" ID="TextBoxDuration" Width="250"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TextBoxDuration" runat="server" ErrorMessage="Dieses Feld darf nicht leer sein" /><br />
<asp:RegularExpressionValidator runat="server" ControlToValidate="TextBoxDuration" validationexpression="((\d+)((\.\d{1})?))$" ErrorMessage="Nur Zahlen" />
users can still input the char e and +, -
I don't like to use normal Textbox with the same Regularexpressionvalidator (which actually would work)
example:
You can simply use regular expression validator as
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="TextBox1" runat="server"
ErrorMessage="Only Numbers allowed"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>
Also you can use the below regular expression to make the text-field as 12 digit number to be added.(madatory)
^[0-9]{12}$
Also you can make the field as between 10 and 12 digits (mandatory) as below
^[0-9]{10-12}$
You can use RegularExpressionValidator for this. below is the sample code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Only Numbers allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>
above TextBox only allowed integer to be entered because in RegularExpressionValidator has field called ValidationExpression, which validate the TextBox. However, you can modify as per your requirement.
You can see more example in MVC and Jquery here.
You can use jQuery like this
Number : <input type="text" name="quantity" id="quantity" /> <span id="errmsg"></span>
<script>
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
</script>
you can make a Javascript function into your Textbox.
Try <asp:TextBox ID="txtNumero" Text="" onkeydown="return jsDecimals(event);" Width="75px" runat="server"></asp:TextBox>
Then
function jsDecimals(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
//Here is where respond with 0 o 1.
if (!jsIsUserFriendlyChar(key, "Decimals")) {
return false;
}
}
else {
if (evt.shiftKey) {
return false;
}
}
}
return true;
}
REGEX
^[0-9]*$
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tbAccount"
ErrorMessage="Please Enter Only Numbers" ForeColor="Red" ValidationExpression="^\d+$"> </asp:RegularExpressionValidator>
IF YOU DON'T WANT USER TO TYPE OTHER CHARACTER ON KEY EVENT THEN
$('#TEXTBOXID').keypress(function (e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
// allow a max of 1 decimal point to be entered
if (!(a.indexOf(k) >= 0)) e.preventDefault();
});
you can use filter textbox extender.
it will allows only number.
there is no negative numbers or e,+,- keys
<asp:FilteredTextBoxExtender ID="TextBox1_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtDay" FilterType="Numbers"> </asp:FilteredTextBoxExtender>
You can also use asp.net field validate like this
<asp:TextBox runat="server" CssClass="form-control" ID="txtNumero" />
<asp:RegularExpressionValidator
ID="txtNumero"
ControlToValidate="EmailTextBox"
Text="(Invalid number)"
ForeColor="Red"
ValidationExpression="^\d+$"
runat="server" />
In the code-behind, just set
this.TextBoxDuration.Attributes["type"] = "number";
Adding Type="number" will work.
<asp:TextBox ID="txtQty" type="number" runat="server"></asp:TextBox>

Validating textbox only if checkbox is checked - no post back

I have a asp.net CheckBox and I have a textbox, I only want textbox to validate when checkbox is checked otherwise just leave it like this.
I find MVC post but I want for asp.net forms Validating textbox only if checkbox is checked using MVC
This is my current code which validates textbox regardless of checkbox is checked or not,
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" ErrorMessage="You must enter a subject." runat="server" />
You will need a custom validator ,then:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CustomValidator ControlToValidate="txtSubject" OnServerValidate="IsTextboxValid" Text="Text box is invalid" runat="server"/>
In code behind,define custom validation method:
protected void IsTextboxValid(object sender,ServerValidateEventArgs e)
{
e.IsValid=chkSubjectRequired.Checked;
}
Please note that this is Server-side Validation
this is what you looking for. Just enable/disable the validator (also textbox if you want) that's all.
Validate The Text Box Only Number :
<input type="text" onkeydown="ValidateNumber(event);">
<script>
function ValidateNumber(e) {
if ((e.keyCode >= 8 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
return true
}
return false;
};

Obtaining control Id through javascript in asp.net

I have a scenario in my asp.net application where when enter button is keyed in any of the multiline textboxs, I need to add a particular length to the existing length and show it in another control. I have written a generic javascript function to handle key-in in "pnlEnglish" panel. I can find out "Enter key" key up by checking "e.keycode ==13" , However would it be possible to know from which control I am firing the event??. I am trying to avoid adding events to text box since, I have to handle it for too many. Is there any better solution to achieve this??
<asp:Panel ID="pnlEnglish" runat="server">
<asp:TextBox ID="txtPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px" TabIndex="12"></asp:TextBox>
<asp:TextBox ID="txtLegacyPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px"TabIndex="12"></asp:TextBox>
</asp:Panel>
Javascript is as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
//Need to identify the control for which I shall add the length
}
var txtLenPlot = $('#<%=txtPlot.ClientID%>').val().length;
var txtLenLegacyPlot = $('#<%=txtLegacyPlot.ClientID%>').val().length;
//The below function shows the length in length displaying control
update_chars_left(500, $('#<%=txtLengthPlot.ClientID %>'), txtLenPlot);
update_chars_left(205, $('#<%=txtLengthLegacyPlot.ClientID %>'), txtLenLegacyPlot);
});
In side key up function you can get id of textbox in which enter key is pressed as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
var currTextboxId = $(this).attr('id');
//Your Code
});

jquery onblur empty textbox validation on asp:textboxes

I have a series of asp:textboxes (about 30) which I wanted to validate if they are empty (when the user goes to other textbox), when the users leave them empty (on blur) I have found tutorials on the net however it is specified only to a few textboxes, how can I achieve this?
<form id="form1" runat="server">
<asp:TextBox ID="txtLname" runat="server" placeholder="Last Name" BackColor="White" BorderColor="#C2C4CC" BorderStyle="Solid" Height="28px" Width="135px" title="Enter Your Last Name" onkeypress="return AllowAlphabet(event)" Enabled="False" TabIndex="4"></asp:TextBox>
A little bit of your actual markup would come in handy, but from the information i have:
$('input, textarea').blur(function() {
if ($(this).val() == "") alert("empty!");
});
when the users leave them empty (on blur) I have found tutorials on
the net
How is this a sentence?
Try this code:
function CheckEmptyCheckBox() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
})
alert(empty + ' empty input(s)')
}

Password custom validation ain't working

I have a form for registration.
I'm checking if the password has 6 characters like this :
<input type="password" runat="server" name="password" size="41" maxlength="64" id="txtpassword" /><span>*</span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="Fill in a password." ControlToValidate="txtpassword"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="valPassword" ErrorMessage="Password must be 6 characters long." ControlToValidate="txtpassword"></asp:CustomValidator> (at least 6 characters)
codebehind
protected void valPassword(object source, ServerValidateEventArgs args)
{
args.IsValid = ValidatePassword(args.Value);
}
private bool ValidatePassword(string pw)
{
if (pw.Length >= 6)
{
return true;
}
else
{
return false;
}
}
If I leave the RequiredFieldValidator and the CustomValidator work together and I fill in 1 character , the form is accepted.
If I delete the RequiredFiekdValidator and fill in the form, the form is accepted with no character at all in the passwordfield
If I leave the CustomValidator and I fill in 1 character , the form is accepted
My CustomValidator isn't working properly, what am I missing ?
try changing txtpassword to an <asp:Textbox> instead of an input.
maybe a problem with name vs id? I usually try to have the name and the id of an element match to avoid confusion.

Categories