I need to do validation on text box such that it can only accept integers from 3 to 1440 or "Default" word. range validator control does not work in this case and probably have to use custom validator control and jquery I am assuming.anyone with a solution similar to this?
Asked
Active
Viewed 68 times
2
-
Because the "default" value there is no ready implementation for it, but you can write your on custom validation attribute http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/mvc-4-custom-validation-data-annotation-attribute/ – Lucas Roselli Sep 23 '15 at 20:29
3 Answers
3
You can follow below example for your requirement:
<input type="text" id="txtbox" runat="server" onchange="javascript:return validateRange();" />
Javascript code:
<script type="text/javascript">
function validateRange() {
var txtVal = document.getElementById("<%=txtbox.ClientID%>").value;
if ((txtVal >= 3 && txtVal <= 1440) ||(txtVal == "Default")) {
return true;
}
else
alert('Please enter a number between 3-1400 or Default');//Also you can set this message to an existing label
return false;
}
</script>

Ruchi
- 1,238
- 11
- 32
-
this works great thanks. how do you make sure this txtval is integer and not accept any decimal numbers? – NoStressDeveloper Sep 23 '15 at 21:08
-
I hope these links will be helpful : http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript – Ruchi Sep 24 '15 at 14:02
-
http://stackoverflow.com/questions/3885817/how-to-check-that-a-number-is-float-or-integer – Ruchi Sep 24 '15 at 14:03
-
Please do mark the answer as correct, if it worked for you. Thank you :) @avi – Ruchi Sep 24 '15 at 14:05
-
I do not see any option to mark this as correct answer .How do I do that? :) – NoStressDeveloper Sep 24 '15 at 17:32
-
There is correct check beneath "2" upvotes marked near my answer. Clicking that marks the correct answer. – Ruchi Sep 24 '15 at 18:11
0
Create a custom validation attribute
public class CustomRangeValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string inputValue= value.ToString();
if (some if statement)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Please Enter a Valid Email.");
}
}
else
{
return new ValidationResult("" + validationContext.DisplayName + " is required");
}
}
then in your class:
[CustomRangeValidator]
public string Email { get; set; }

Ruchi
- 1,238
- 11
- 32

Lucas Roselli
- 2,810
- 1
- 15
- 18
0
My question needed a validation for integers and all cases of default too. so i used following in addition to @ruchi rahul answer.
if ((txtVal >= 3 && txtVal <= 1440 && txtVal%1===0) || (txtVal.toUpperCase() == "Default".toUpperCase()))

NoStressDeveloper
- 491
- 3
- 9
- 26