I have 3 text box which takes values postal code & mobile number & residential number. I got the solution for allowing only number in text box using jquery from Bellow post.
I would like to make an EditFor textbox accept numbers only
but can we do this using data annotations as I am using MVC4 razor ?
This question is related to
asp.net-mvc
asp.net-mvc-3
asp.net-mvc-4
Use this function in your script and put a span near textbox to show the error message
$(document).ready(function () {
$(".digit").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errormsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
@Html.TextBoxFor(x => x.company.ContactNumber, new { @class = "digit" })
<span id="errormsg"></span>
Here is the javascript that will allows you to enter only numbers.
Subscribe to onkeypress
event for textbox.
@Html.TextBoxFor(m=>m.Phone,new { @onkeypress="OnlyNumeric(this);"})
Here is the javascript for it:
<script type="text/javascript">
function OnlyNumeric(e) {
if ((e.which < 48 || e.which > 57)) {
if (e.which == 8 || e.which == 46 || e.which == 0) {
return true;
}
else {
return false;
}
}
}
</script>
Hope it helps you.
DataType
has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint
attribute.
Adding a new core DataType is not possible since the DataType
enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute
. Then you can add a new constructor with your own DataType
enumeration.
public NewDataTypeAttribute(DataType dataType) : base(dataType)
{ }
public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();
You can also go through this link. But I will recommend you using Jquery for the same.
@Html.TextBoxFor(m => m.PositiveNumber,
new { @type = "number", @class = "span4", @min = "0" })
in MVC 5 with Razor you can add any html input attribute in the anonymous object as per above example to allow only positive numbers into the input field.
in textbox write this code onkeypress="return isNumberKey(event)"
and function for this is just below.
<script type="text/javascript">
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<input type="number" @bind="Quantity" class="txt2" />
Use the type="number"
for decimal values greater than zero, HTML5 works as follows:
<input id="txtMyDecimal" min="0" step="any" type="number">
i was just playing around with HTML5 input type=number. while its not supported by all browsers I expect it is the way going forward to handle type specific handling (number for ex). pretty simple to do with razor (ex is VB)
@Html.TextBoxFor(Function(model) model.Port, New With {.type = "number"})
and thanks to Lee Richardson, the c# way
@Html.TextBoxFor(i => i.Port, new { @type = "number" })
beyond the scope of the question but you could do this same approach for any html5 input type
@Html.TextBoxFor(x => x.MobileNo, new { @class = "digit" , @maxlength = "10"})
@section Scripts
{
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(".digit").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
{
$("#errormsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
</script>
}
Use a regular expression, e.g.
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Count must be a natural number")]
public int Count { get; set; }
can we do this using data annotations as I am using MVC4 razor ?
No, as I understand your question, unobtrusive validation will only show erorrs. The simplest way is use jquery plugin:
function NumValidate(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert('Only Number ');
return false;
} return true;
} function NumValidateWithDecimal(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
alert('Only Number With desimal e.g.: 0.0');
return false;
}
else {
return true;
} } function onlyAlphabets(e) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
return true;
else
alert("Only text And White Space And . Allow");
return false;
}
catch (err) {
alert(err.Description);
}} function checkAlphaNumeric(e) {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
return true;
} else {
alert('Only Text And Number');
return false;
}}
Please use DataType attribue but this will except negative values so the regular expression below will avoid this
[DataType(DataType.PhoneNumber,ErrorMessage="Not a number")]
[Display(Name = "Oxygen")]
[RegularExpression( @"^\d+$")]
[Required(ErrorMessage="{0} is required")]
[Range(0,30,ErrorMessage="Please use values between 0 to 30")]
public int Oxygen { get; set; }
Hi try the following....
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName, new {onkeydown="return ValidateNumber(event);" })%>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
SCRIPT
<script type="text/javascript">
function ValidateNumber(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
};
This worked for me :
<input type="text" class="numericOnly" placeholder="Search" id="txtSearch">
Javacript:
//Allow users to enter numbers only
$(".numericOnly").bind('keypress', function (e) {
if (e.keyCode == '9' || e.keyCode == '16') {
return;
}
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (e.which == 46)
return false;
if (code == 8 || code == 46)
return true;
if (code < 48 || code > 57)
return false;
});
//Disable paste
$(".numericOnly").bind("paste", function (e) {
e.preventDefault();
});
$(".numericOnly").bind('mouseenter', function (e) {
var val = $(this).val();
if (val != '0') {
val = val.replace(/[^0-9]+/g, "")
$(this).val(val);
}
});
Maybe you can use the [Integer] data annotation (If you use the DataAnnotationsExtensions http://dataannotationsextensions.org/) . However, this wil only check if the value is an integer, nót if it is filled in (So you may also need the [Required] attribute).
If you enable Unobtrusive Validation it will validate it clientside, but you should also use Modelstate.Valid in your POST action to decline it in case people have Javascript disabled.
Source: Stackoverflow.com