MVC-type validation - asp.net-mvc-2

Hey i have model and it looks like this:
[Required(ErrorMessage = "Morate unijeti vrijednost")]
public int Cijena{ set; get; }
If user doesn't enter value , my error message is being written, but if user enter value that is not int I got this message "The value '' is not valid for Cijena" . How can I overwrite this message with custom one?
Thx

Use a regular expression validator as well
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.95).aspx
[RegularExpression(Pattern=#"\d+", ErrorMessage="only numbers please")]

Related

MVC 5 Entity Frame work display name not allowing to enter ten digit number giving error "Value is not valid for"?

i have this property in my entity class,
[Display(Name = "Phone", ResourceType = typeof(Resources.Resource))]
public Nullable<int> Phone { get; set; }
i enter ten digit number it gives me error
"The value '5698452136' is not valid for"
if i enter 9 digits than ok
i have not apply any validation just display name according to language.
But id i remove Display property it works fine. why it is giving me validation error ?
EDITED:
Sorry my mistake on my required attribute it is giving this error,
[Required(ErrorMessageResourceType = typeof(Resources.Resource),
ErrorMessageResourceName = "PhoneRequired")]
after adding above required i am getting error as i mentioned above and works fine if i remove it
Hopes for your suggestions
Hopes for your suggestions
You want to change type from int to long as max value for integer is 2,147,483,647 and you are trying to pass 5,698,452,136 which exceeds the upper boundary.
[Display(Name = "Phone", ResourceType = typeof(Resources.Resource))]
[Required(ErrorMessageResourceType = typeof(Resources.Resource),
ErrorMessageResourceName = "PhoneRequired")]
public Nullable<long> Phone { get; set; }

My (ko.) validation based on a regex doesn't work with some inputs

I try to set validation in place for my amount field. I allow only numeric characters. I choose to use regex for my validation.
My model server side:
public class InvoiceLine
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
public double Amount { get; set; }
}
The regex for the validation of my amount client side:
invoiceLine.amount.extend({
pattern: {
message: 'warning!',
params: '^[1-9]\d*$'
}
});
Then in my view:
<input type="text" data-bind="value: amount, valueUpdate: 'afterkeydown', validationOptions: { errorElementClass: 'input-validation-error' }" />
The tests:
123 valid OK
azerty invalid OK
123abc valid NOK
In the tests above, when I say 'valid/invalid' I mean the validation success/failed, when I say 'OK/ NOK' I mean this validation is what I expected/don't expected.
So the third test is not what I expected and I don't know why ko.validation don't mark it as invalid. It seems that whenever the first character is a numeric, no matter what is next, it is not marked as invalid.
Then for testing purpose I changed my model server side from:
public double Amount to public string Amount and the result is:
123 valid OK
azerty invalid OK
123abc invalid OK
So it seems that the behaviour is better with a string than a double BUT I need a double field for my amount that make more sence!
Any idea how to have a fully satisfied validation on my amount when keeping a double type for this field?
Thanks.

simple MVC EF query

I am a MVC EF newb.
I'm trying to do a very simple query. Maybe I'm thinking about it too much in the "SELECT * FROM TABLE WHERE BLAHBLAH > 3" format and not in a class-based MVC EF layout.
Anyway I have a model/class called "Messages". I'm trying to get all the messages with a specific username. So I have something like this:
var mesg = from msg in elkdb.Messages
where mydb.Messages.user = Membership.GetUser()
select msg;
Visual web developer flags the .msg part of the "where" line and says:
Error 2
'System.Data.Entity.DbSet'
does not contain a definition for
'msg' and no extension method 'msg'
accepting a first argument of type
'System.Data.Entity.DbSet'
could be found (are you missing a
using directive or an assembly
reference?)
msg is defined in the class as follows:
public class Message
{
public long ID { get; set; }
...
public string msg { get; set; }
}
And I know I have scope access to Message at this point.
Am I laying this out wrong? Do I just have the syntax incorrect?
Thanks for your help!
EDIT: I mistakenly had "mydb.Messages.msg = Membership.GetUser()" earlier because it was way past my bedtime.
I think the query are wrong
var mesg = from MSG in elkdb.Messages
where MSG.msg == Membership.GetUser()
select MSG;
does the msg prop match with UserName?

ASP.Net MVC 2 Model Validation Regex Validator fails

I have following property in my Model Metadata class:
[Required(ErrorMessage = "Spent On is required")]
[RegularExpression(#"[0-1][0-9]/[0-3][0-9]/20[12][0-9]",
ErrorMessage = "Please enter date in mm/dd/yyyy format")]
[DataType(DataType.Date)]
[DisplayName("Spent On")]
public DateTime SpentOn { get; set; }
But whenever I call ModelState.IsValid it always returns false because regex is not validating. I have matched the entered date (08/29/2010) against new regex using same pattern and it matches perfectly.
What am I doing wrong?
Actualy there is another workaround for this. You can simply subclass the RegularExpressionAttribute
public class DateFormatValidatorAttribute : RegularExpressionAttribute {
public DateFormatValidatorAttribute()
: base(#"[0-1][0-9]/[0-3][0-9]/20[12][0-9]")
{
ErrorMessage = "Please enter date in mm/dd/yyyy format";
}
public override bool IsValid(object value) {
return true;
}
}
in your Global.asax.cs on application start register the RegularExpression addapter for client side validation like so:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(DateFormatValidatorAttribute),
typeof(RegularExpressionAttributeAdapter));
Now you get to have the build-in MVC regular exression validator client side and keep the DateTime as your property type
That's because regex applies to strings and not DateTime properties. If the user enters an invalid string which cannot be parsed to a DateTime instance from the model binder it will add a generic error message before your regex pattern executes.
You have a couple of possibilities:
Customize the error message in a resource file
Write a custom model binder
Use a string property (I feel guilty for proposing this :-))

How to change ErrorMessage property of the DataAnnotation validation in MVC2.0

My task is to change the ErrorMessage property of the DataAnnotation validation attribute in MVC2.0. For example I should be able to pass an ID instead of the actual error message for the Model property and use that ID to retrieve some content(error message) from a another service e.g database, and display that error message in the View instead of the ID. In order to do this I need to set the DataAnnotation validation attribute’s ErrorMessage property.
[StringLength(2, ErrorMessage = "EmailContentID.")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
It seems like an easy task by just overriding the DataAnnotationsModelValidatorProvider ‘s
protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
However it seems to be a complicated enough.
a. MVC DatannotationsModelValidator’s ErrorMessage property is read only. So I cannot set anything here
b. System.ComponentModel.DataAnnotationErrorMessage property(get and set) which is already set in MVC DatannotationsModelValidator so we cannot set again. If you try to set you get “The property cannot set more than once…” error message appears.
public class CustomDataAnnotationProvider : DataAnnotationsModelValidatorProvider
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
IEnumerable<ModelValidator> validators = base.GetValidators(metadata, context, attributes);
foreach (ValidationAttribute validator in validators.OfType<ValidationAttribute>())
{
messageId = validator.ErrorMessage;
validator.ErrorMessage = "Error string from DB And" + messageId ;
}
//......
}
}
Can anyone please help me on this?
Here is the question: What is your motivation to changing the error message property?
Think this through very carefully, as you are heading down a path where you are obfuscating what is actually happening in the application. Certainly the database informatino is useful, but it is not really part of the validation, nor should it be.
When you head in this direction, you are essentially saying that the validation can only be invalid if there is a database problem. I see two issues with this:
It breaks the separation of concerns. You are reporting a persistance error in the model, which is not where it occurred.
The solution is not unit testable, as you must engage the database.
I don't like either of the two above.
Can you solve this? Possibly if you will create your own custom validation attribute. I would have to check and ensure that is correct. Another option is to aim for custom validation:
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
This article can also help you head in the direction you desire:
http://ryanrivest.com/blog/archive/2010/01/15/reusable-validation-error-message-resource-strings-for-dataannotations.aspx
Do you want to solve this? Not really if you are attempting to keep a proper separation of concerns in your application. I would not polute my validation error message (this is not valid) with a database error (I am not valid, but the database also blew up). Just my two cents.
There are built in ways to get the error message via a resource. Instead of a database lookup to get a resource at runtime, generate resources from your database and use that for your error messages.
You can then use the ErrorMessageResourceName and ErrorMessageResourceType to allow the DataAnnotation to perform a resource lookup instead of hard-coding a specific string.
public sealed class MyModel
{
[Required(
ErrorMessageResourceName="MyDescriptionResource",
ErrorMessageResourceType=typeof(MyCustomResource))]
public string Description { get; set; }
}
Also you may want to have a look at ValidationAttribute.FormatErrorMessage Method on msdn.
This method formats an error message
by using the ErrorMessageString
property. This method appends the name
of the data field that triggered the
error to the formatted error message.
You can customize how the error
message is formatted by creating a
derived class that overrides this
method.
A quick sample (and not meant to be a definitive example)
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false,
Inherited = true)]
public sealed class PostCodeValidationAttribute
: ValidationAttribute
{
public override bool IsValid(object value)
{
if( value == null )
return true;
string postCode = value as string;
if( string.IsNullOrEmpty(postCode) )
return true;
if ( !PostCode.IsValidPostCode(postCode, this.PostCodeStyle) )
return false;
return true;
}
public PostCodeStyle PostCodeStyle { get; set; }
public override string FormatErrorMessage(string name)
{
return string.Format(
"{0} is not a valid postcode for {1}", name, PostCodeStyle);
}
}
* I've omitted the PostCodeStyle enumeration as well as the PostCode class for validating a postcode.