I have a int property in my class and want to validate if the user has entered a string.
How can I do that using data annotations?
When I pass a non-integer value I get a excpetion like this:
The value 'asdasd' is not valid for property.
For example using this validation attribute:
[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }
and entering 'aaa' in a field tha uses the model I've got an excepetion with this message:
The value 'aaa' is not valid for Number.
Instead of the "Invalid Number" message.
Any Ideas?
I've put
[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }
but I've got this message from an excpetion
The value 'aaa' is not valid for Number.
There are two stages of validation at play here.
Before the validation set up in your attributes is called, the framework first attempts to parse the information.
So here are a couple of examples based on this code:
[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }
I type nothing into the box...
"Invalid Number" (Framework will create a null integer, your validation rule fails)
I type "A" into the box...
"The value 'A' is not valid for Number." (Framework cannot convert "A" into a nullable int, so the framework validation rule fails and your validation rule it not checked.
** Solutions **
1 - Live with the default message until you are using MVC 3 / .NET 4, which makes it easier to override these messages
2 - Exclude the value from the binder, so it won't cause an error (but you will have to bind it and check it yourself)
[Bind(Exclude="MyNumber")]
3 - Make it a string on the model, then test it with a TryParse and add your own custom model error (This is a reasonable practice and reminds us all why View Models are used rather than Domain Objects!)
if (!Int32.TryParse("MyNumber", out myInteger)) {
ModelState.AddModelError("MyNumber", "That isn't a number!");
}
There are actually lots of solutions, but I would say go with option 3 for now.
You could put a Range-attribute on your model-field like so:
[Range(0, 9999)]
public int Something {get; set;}
Now whenever the user inputs a string it will not validate, and also the int must be between 0-9999
this should also work with
[Range(0, 9999)]
public string Something {get; set;}
and
[Range(0, 9999)]
public object Something {get; set;}
Related
I have ASP.Net WebAPI based application. Below is my DTO.
public class CustomerTO
{
[Required(ErrorMessage="Name required")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Name invalid")]
public string Name { get; set; }
[Required(ErrorMessage="CountryId required")]
[Range(1,250,ErrorMessage="CountryId invalid")]
public int Country { get; set; }
}
My API Controller.
[HttpPost]
[AllowAnonymous]
public HttpResponseMessage Post([FromBody]CustomerTO model)
{
if (ModelState.IsValid)
{
//my stuff
}
else
{
var msg = ModelState.SelectMany(s => s.Value.Errors).FirstOrDefault().ErrorMessage;
}
}
If user passed any of the required field as Null, it returns the right Error message mentioned in the Data Annotations while if I pass string for CountryId, it enters into else condition(*ModelState.IsValid = false*)
But the ErrorMessage is empty.
While If I debug & put the below statement in quick watch.
msg = ModelState.SelectMany(s => s.Value.Errors).FirstOrDefault().Exception.Message;
It returns - Could not convert string to integer: en. Path 'Country', line 6, position 14.
Why in this scenario, I am not getting the Error message as CountryId Invalid
How do I get this?
Using a RegularExpressionAttribute does not prevent RangeAttribute from throwing an "Could not convert string to integer" exception. So just filter the right one:
var msg = ModelState.SelectMany(s => s.Value.Errors)
.FirstOrDefault(_ => _.Exception == null)
.ErrorMessage;
As far as I know, it is a common problem: SO question 1, SO question 2.
According to code, from any validation attribute there is creating a wrapper, derived from RequestFieldValidatorBase. Each wrapper calls IsValid method of ValidationAttribute. In the method Validate of RequestFieldValidatorBase passing form value for validation.
So, RequiredAttribute does not fails, because form value is not empty and is not null, and RangeAttribute does not fails, because it has problems converting this value to int.
To achieve your desired behaviour it is recommend to create your own validation attribute or use a RegularExpressionAttribute. You can take a look at this answer.
I believe the range validators dont cater for string entry, i.e. they only fire if it's a valid integer. It doesn't enforce the type passed in.
Try changing your annotation to a regex.
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Country code invalid")]
public string Country { get; set; }
With reference to this link Integer validation against non-required attributes in MVC
As dirty patch, I modified my property from int to string & decorated it with Regular Expression.
I've trying to validate a property on a model I have. This property is NOT required, and so if its invalid MVC seems to be ignoring it. I've even created a custom ValidationAttribute, but nothing works.
public class NumberWang : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return true;
int g;
if (int.TryParse(value.ToString(), out g))
{
if (g >= 0)
return true;
}
return false;
}
}
public class MyModel
{
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
[NumberWang(ErrorMessage = "That's NumberWang!")]
public int? category_id { get; set; }
/* there are other properties of course, but I've omitted them for simplicity */
public void Validate()
{
Validator.TryValidateProperty(this.category_id,
new ValidationContext(this, null, null) { MemberName = "category_id" },
this.validation_results);
}
}
If I pass the value 'abc' as a category_id to this model, it validates just fine. What am I doing wrong?
I found an ugly workaround.
It seems that if category_id is a nullable int? and my value is not a valid number, a null value is passed, and the model doesn't see the invalid 'abc' value.
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public int? category_id { get; set; }
// when we pass a good number
MyAction?category_id=123
validation: successful
// when we pass a bad number
// validation ignores it. not what we want.
MyAction?category_id=abc
validation: successful
If I change category_id to a non-nullable int, it fails validation even when no value is passed.
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public int? category_id { get; set; }
// when we pass a good number
MyAction?category_id=123
validation: successful
// when we pass an bad number
MyAction?category_id=abc
validation: "category_id must be a valid number"
// BUT, when we don't pass any number at all ...
MyAction
validation: "category_id must be a valid number"
The Ugly Workaround
If I change category_id to a string, and then only convert it to an int when I need it, I can validate it properly, using only [Range]
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public string category_id { get; set; }
// when we pass a good number
MyAction?category_id=123
validation: successful
// when we pass a bad number
MyAction?category_id=abc
validation: "category_id must be a valid number"
// no number, no validation. hooray!
MyAction
validation: successful
It's ugly, but it works.
(Note: the custom attribute was not needed, so I removed it and just used [Range])
model:
// "(\s*[0-9]{0,6})" for 999999 max
// "(\s*[0-9]*)" for "infinite"
[RegularExpression(#"(\s*[0-9]{0,6})", ErrorMessage = "Field must be a natural number (max 999999)")]
public int? Quantity { get; set; }
view:
#Html.TextBoxFor(m => m.Quantity)
#Html.ValidationMessageFor(m => m.Quantity)
First your model should implement IValidatableObject, but the Validate method is going to be called only if the ModelState is valid. This link can help.
Are you receiving your model as a parameter in the action? Are you asking for the ModelState.IsValid? This should work fine with the Default model binder.
I found a workaround that I kind of like. The problem I ran into was a similar issue, where the value had to be greater than 0 and a number, so once I tried to cast the 9999999999 (invalid) string as a number it threw an exception and didn't show that the model state has an error message on the post. I hope this is on topic since it sounds like "Rules don't seem to apply correctly when I type in an invalid number"
Since my number had to be positive I intercepted the value into an anonymous type object (dynamic) and used it as an intercepting body between the model's user and the private int property. When I did that, the Data Annotations worked as expected.
public dynamic MyProperty
{
get { return _myProperty; }
set
{
try
{
/I have to convert the value to String because it comes in as String[], and if there is more than one value then it should be problematic, so you join it together with an invalid character and throw an error, or you take the first value/
_myProperty = = Convert.ToInt32(String.Join("a",value));
}
catch (Exception e)
{
_myProperty= -1;
}
}
}
private int _myProperty;
I have the following attribute on my field:
[Range(-1,200)]
public decimal MyValue{ get; set; }
If I enter any value that doesn't fall in the range I get:
The field must be between -1 and 200
This is fine.
Here's the problem, I'm getting "The field must be a number" validation message when I enter zero which is a valid value.
Any suggestions?
Thanks
I think this may be happening due to the decimal type. Try this:
[Range(typeof(Decimal),"-1", "200")]
public decimal MyValue{ get; set; }
Source.
I'm working on an MVC app, and a bit of model code I've written has unfolded somewhat like this:
public class SomeModel
{
public int? CodeA { get; set; }
public int? CodeB { get; set; }
[RequiredIf("CodeA", 3, ErrorMessage = "(required for [Something]!)")]
[RequiredIf("CodeB", 99, ErrorMessage = "(required for [Other]!)")]
public string Foo { get; set; }
// SNIP: Unimportant details
}
Note: The RequiredIf() implementation I am using is found here.
I have decorated property Foo, which a user has the ability to edit in certain circumstances, with two RequiredIf() attributes. There are two different cases in which it is required to be filled out. In all other circumstances, the front end will parse the user's input and populate it for them 'behind' the scenes.
Question: If only one case (e.g. CodeA = 3, CodeB = 4) is satisified, and the user fails to enter anything thus causing a negative validation, will the model still be marked as Invalid and a ErrorMessage logged for it? Or, since the Code B condition is satisfied, will that override the validation performed if CodeA is in a state that it is required (and not entered)?
Another way of asking: are validations additive, or is there an implicit limit to the results of only one validation at a time?
Validation is negative. For validation to pass, ALL validators must confirm the field is valid. So for your Foo, if the CodeA validator passes and the CodeB validator fails, validation will fail. Modelstate will contain a single error for that field. If both fail, modelstate will contain two errors for that field.
I have a basic DTO object which I am trying to update, I noticed if I post some data from the UI to the controller and I enter string inside a decimal field the data annotations validation does not pick this up, in fact the string is converted into 0 for some reason...
How do I get my decimal values to remain decimal i.e. throw an error if a string is added, do I need to create a custom value provider for this DTO object?
My DTO:
public class FeesDTO
{
public int ID{ get; set; }
//[DataType( DataType.Currency)]
//[DisplayFormat(ApplyFormatInEditMode=true)]
public decimal ClientFee { get; set; }
public string VAT { get; set; }
public string GrossProfit { get; set; }
}
If I want to update my fees and I enter 'something' inside the ClientFee field this turns the string input into 0...
NOTE:
The commented out data annotations did not work... Is this the correct way to do this?
when you enter a string value e.g "xyz" for ClientFee which is a decimal variable, it can not be converted to decimal and you will get 0 as value of clientfee but when form is rendered again you will see validation message telling you that
xyz is not valid for field clientfee
this is perhaps due to the fact that when modelbinder fail to convert xyz to decimal it adds the error in Modelstate dictionary's error collection. you can make this value string in your viewmodel and validate it yourself using regex and when you are to store it to db you can convert it to your entity with AutoMapper to similar utility.
I think you need to be using the Data Annotation validators:
http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs
Implement one on the Decimal field that throws a validation error if the Control is posted to with a non decimal entry.