asp.net Textbox Textmode Number, allow numbers only - c#

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>

Related

Regex for one letter and 6 numbers in C#

Entering the user number in the text box with the webmethod GetSearchUser returns the name of user.
I have this regular expression to test if an input starts with the letter "a" or "A" and is followed by 6 numbers. On the online validator seems to work.
The problem is that when the user number is replaced with the the name of user this string is not validated. And it is correct.
But how do I then check that user number is entered correctly and validate the string when the user number is replaced with the the name of user?
My code below.
<asp:AutoCompleteExtender
ServiceMethod="GetSearchUser"
ServicePath="prefix.aspx"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txuser"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false">
</asp:AutoCompleteExtender>
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator29" runat="server" ControlToValidate="txuser"
SetFocusOnError="true" ErrorMessage="Required" Text=""
Display="None" ValidationGroup="ValidationSummaryUser"
CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator8" runat="server" ControlToValidate="txuser"
SetFocusOnError="true" ErrorMessage="Required : AXXXXXX" Text=""
Display="None" ValidationExpression="/^(a|A)([0-9]{6})$/" ValidationGroup="ValidationSummaryUser"
CssClass="validation-summary-errors-one"></asp:RegularExpressionValidator>
[ScriptMethod()]
[WebMethod]
public static List<string> GetSearchUser(string prefixText)
{
DataTable Result = new DataTable();
string str = #String.Format("SELECT Name FROM `users` ");
str += String.Format(" WHERE user_number LIKE '" + prefixText + "%' ");
str += String.Format(" ORDER BY Name ASC;");
using (OdbcConnection con =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
da = new OdbcDataAdapter(str, con);
dt = new DataTable();
da.Fill(dt);
List<string> Output = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
Output.Add(dt.Rows[i][0].ToString());
return Output;
}
}
EDIT
According to your description, I'm afraid that the <asp:RegularExpressionValidator> is unable to complete two validations at the same time.
What you need might be a custom validator which could do both validation for the text box.
Solution: using <asp:CustomValidator>
You could do validation from both server side and client side (I did it from client side).
It can be used as a combination of RequiredValidator, RegularExpressionValidator and extra custom style validation.
More details, you could refer to below code:
.aspx :
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<ajaxToolkit:AutoCompleteExtender
OnClientItemSelected="itemSelected"
ServiceMethod="GetSearchUser"
ServicePath="AutoCompleteExtenderValidation.aspx"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="10"
TargetControlID="txuser"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false">
</ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<asp:HiddenField ID="hf_txuser" runat="server" />
<asp:CustomValidator ID="CustomValidatorFortxuser" runat="server"
ClientValidationFunction="custom_validation" ControlToValidate="txuser"
Display="Dynamic" ErrorMessage="Required AXXXX or Valid UserName"
ValidationGroup="ValidationSummaryUser" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<asp:Button ID="SubmitBtn" runat="server" ValidationGroup="ValidationSummaryUser" Text="Submit" OnClick="Submit_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
Javascript code:
<script type="text/javascript">
function itemSelected(sender, ev) {
//When selected value from the return list, it will be kept in the hidden field for the following validation
var selectedValue = ev._value;
$('#<%= hf_txuser.ClientID%>').val(selectedValue);
}
function custom_validation(source, arguments) {
if (arguments.Value == "") {
arguments.IsValid = false;
} else {
//Valid if one of checks pass: fulfill the regex or equals to hidden field value. No worries about the empty content
arguments.IsValid = (regexValidate(arguments) || arguments.Value == $('#<%= hf_txuser.ClientID%>').val());
}
if (!arguments.IsValid) {
$('#<%= Label1.ClientID%>').text("");
}
}
function regexValidate(input) {
var patt = /^(a|A)([0-9]{6})$/;
return patt.test(input);
}
</script>
.cs code:
protected void Submit_Click(object sender, EventArgs e)
{
Label1.Text = txuser.Text + " Submit successfully!";
}
You should include Jquery in the <head> since I have used Jquery in the code for assigning value to the hidden field.
<head runat="server">
<title></title>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
The version could be any one as long as it works for value assignment.
Hope this can help you.

Use server side and client side validation simultaneously on a single form in C#

I have a form (in aspx page) where I am using server side validations (validation controls) and jQuery validations on the same form.
On Textboxes I am using server side validations and on submit button I am using jQuery validation.
I having problem in using both together.
Form:-
<form id="form1" runat="server">
<label>Start Date: </label>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="txtstartDate" ForeColor="Red" Text="*" ValidationGroup="onSave" runat="server" ErrorMessage="Enter start date...!!"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtStartDate" runat="server" CssClass="form-control mytxtCalendar" placeholder="Start Date.."></asp:TextBox>
<label> End Date:</label>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtEndDate" ForeColor="Red" Text="*" ValidationGroup="onSave" runat="server" ErrorMessage="Enter end date...!!"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtEndDate" runat="server" CssClass="form-control mytxtCalendar" placeholder="End Date.."></asp:TextBox>
<asp:Button ID="btnSaveShift" CssClass="btn btn-default" runat="server" Text="Save" ValidationGroup="onSave" OnClick="btnSaveShift_Click" OnClientClick="CheckDateTimes();" />
<asp:ValidationSummary ID="vlsAdd" ValidationGroup="onSave" ForeColor="Red" ShowMessageBox="true" ShowSummary="false" runat="server" />
</form>
jQuery Code:-
function CheckDateTimes() {
var Frm_Date = $("#<%=txtStartDate.ClientID %>").val();
var To_Date = $("#<%=txtEndDate.ClientID %>").val();
if (Frm_Date.length > 0 && To_Date.length > 0) {
if (parseDate(Frm_Date) > parseDate(To_Date)) {
alert('Start date can not be greater than to date...!!');
$("#<%=txtStartDate.ClientID %>").focus();
}
}
}
I have also tried below jQuery functions but these stops server side validations.
$("#btnSaveShift").click(function(evt){
var Frm_Date = $("#<%=txtStartDate.ClientID %>").val();
var To_Date = $("#<%=txtEndDate.ClientID %>").val();
if (Frm_Date.length > 0 && To_Date.length > 0) {
if (parseDate(Frm_Date) > parseDate(To_Date)) {
alert('Start date can not be greater than to date...!!');
$("#<%=txtStartDate.ClientID %>").focus();
evt.preventDefault();
}
}
});
This as well:-
<asp:Button ID="btnSaveShift" CssClass="btn btn-default" runat="server" Text="Save" ValidationGroup="onSave" OnClick="btnSaveShift_Click" OnClientClick="return CheckDateTimes();" />
function CheckDateTimes() {
var Frm_Date = $("#<%=txtStartDate.ClientID %>").val();
var To_Date = $("#<%=txtEndDate.ClientID %>").val();
if (Frm_Date.length > 0 && To_Date.length > 0) {
if (parseDate(Frm_Date) > parseDate(To_Date)) {
alert('Start date can not be greater than to date...!!');
$("#<%=txtStartDate.ClientID %>").focus();
return false;
}
}
return true;
}
If you need to use both OnClick and OnClientClick together with the same button then add a return true or false to OnClientClick function. Please check this link
example
you need to change CheckDateTimes method to return bool value, then you can change JS method call as OnClientClick="return CheckDateTimes();" if this return true only it will call server side. if you need to call server side validation always then return true from the javascript method.
check Asp .NET Button - OnClientClick="return function()" vs OnClientClick="function()"

ASP.NET file size validator not validating

So I have a few ASP.NET file upload controls in my aspx file -
<asp:FileUpload ID="fulNature" class="form-control summer" runat="server" /><asp:Labe ID="lblNature" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="fulNature" Display="Dynamic"
ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>
<asp:FileUpload ID="fulIndustrial" class="form-control summer" runat="server" /><asp:Label ID="lblIndustrial" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="fulIndustrial" Display="Dynamic"
ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>
I'm trying to limit file size with one C# validator -
protected void ValidateFileSize(object source, ServerValidateEventArgs args)
{
var validator = (source as CustomValidator);
string controlToValidate = validator.ControlToValidate;
FileUpload SubmittedUpload = validator.NamingContainer.FindControl(controlToValidate) as FileUpload;
if (SubmittedUpload.FileBytes.Length > 1048576) // A little padding added.
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
The issue is that the validator never fires regardless of file size. I have to be missing something simple here, but I'm just not seeing it.
you can directly get the size of uploaded file:
long size=fulNature.FileContent.Length;
Try:
long filesize = SubmittedUpload.FileContent.Length;

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

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" />

CustomValidation using OnServerValidate and ClientValidationFunction

I have problems in using CustomValidation control, I want to check if year entered in date of birth text field is less than graduation year selected from a drop down list by 20 years. I think using ClientValidationFunction is much better when i tried to use it:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>
here is the script
<script type="text/javascript">
function GraduationYearValidation(sender, args) {
var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);
if ((brithYear - gradeYear) < 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
I get those errors: document.getElementById(...) is null and GraduationYearValidation is not defined.
so, i tried to make it server side by:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>
code behind is :
protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);
if ((gradeYear - brithYear) < 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
it doen't work and i searched for the reason i found it may be because i need to write Page.Validate("SaveEducationStep"); and check if Page.IsValid before save, but it still not working with me
any suggestion on both scenarios will be appreciated. thanks.
client side validation is working, check your code
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:DropDownList ID="dddate" runat="server">
<asp:ListItem Text="2014" Value="2014"></asp:ListItem>
<asp:ListItem Text="2013" Value="2013"></asp:ListItem>
<asp:ListItem Text="2012" Value="2012"></asp:ListItem>
<asp:ListItem Text="2011" Value="2011"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" EnableClientScript="true" runat="server" ErrorMessage="CustomValidator" ValidationGroup="test" ClientValidationFunction="abc" ControlToValidate="dddate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="test" />
<script type="text/javascript">
function abc(sender, args) {
var birthYear = parseInt(new Date(document.getElementById('<%=txtDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=dddate.ClientID%>').options[document.getElementById('<%=dddate.ClientID%>').selectedIndex].text);
if ((gradeYear - birthYear) > 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
</script>

Categories