MVC3 Range validation when value is larger then zero - asp.net-mvc-3

I have a product order page where the minimum order is 2500. I want to use the Range annotation validation in the model to validate this, but I also need the user to be able to select 0 of this product if they don't want any.
Now I use:
[Display(Name = "Item1")]
[Range(1000, int.MaxValue, ErrorMessage = "You need to order minimum {1} of Item1")]
public int OrderedItem1{ get; set; }
Is there an easy way to accomplish this without creating a custom validator?

Yes, you could use the regular expression validation attribute.
[RegularExpression(#"SomeRegExpression", ErrorMessage = "Min order error")]

I found out that I could do this using this regular expression validation attribute:
[RegularExpression(#"^(?:0|\d{5,}|[1-9]\d\d\d)$", ErrorMessage = "You need to order minimum 1000 of Item1")]
Thanks to Ryand Johnson for helping out.

Related

MVC5 StringLength validation failing on int

i have the following validations specified for an int field.
[Required(ErrorMessage = ValidationMessages.ResponseRequired)]
[Digits(ErrorMessage = ValidationMessages.DigitsOnly)]
[StringLength(6, MinimumLength = 6, ErrorMessage = ValidationMessages.InvalidLength)]
public int? Code { get; set; }
When i take out the StringLength then the post is successful. With it, i get 500 exception:
Unable to cast object of type 'System.Int32' to type 'System.String'
What is going on here? Do i need to write a custom one for int? In this case, i just want to make sure that the user is entering 6 digits.
String length isnt really valid for an int, though?
What is it that you are trying to achieve? That the input is greater than 99,999?
Then you can use:
[Range(100000,int.MaxValue)]
You can use Range or RegularExpression for control your digits length.
Range[0,999999]
Range[100000,999999]
[RegularExpression(#"\d{6}")]

magento weight attribute without decimal points

I need to show weight attribute without any decimal points in admin panel on front end that is working fine but I need to remove the 4 decimal points from admin panel where site admin enter the product details.
Any help in terms of code or database changes will be appreciated.
image url : http://sale24by7.com/weight.png
Thanks & Regards
You can use Event
adminhtml_catalog_product_edit_prepare_form
To catch the form output and modify it as you want !
The method will look like this :
public function renderWeight( Varien_Event_Observer $observer )
{
$form = $observer->getForm();
$element = $form->getElement('weight'); // Weight attribute from the Form Data
if($element){
$oldWeight = $element->getValue(); // Weight Value you want to modify
$values['weight'] = (int) $oldWeight; // Assign the new Weight Value
$form->addValues($values); // Add it to the form
}
}
I have created the module you downloaded from here Download
I just use this:
.$this->htmlEscape(number_format($weight));
To change the decimal precision of attributes that have a backend_type set to decimal,
You have to change the type of value in this table :
catalog_product_entity_decimal
If you have not change yet, you should see :
decimal(12,4)
You should replace with
decimal(12,0)

Grails parent child form validation

I have an Invoice
class Invoice{
static hasMany = [lineItems: InvoiceItem]
double total
}
class InvoiceItem{
String description
double price
double qty
}
My issue is with form validation. If a user enters a string or invalid number format in either price or qty I get a
Failed to convert property value of type java.lang.String
to required type double for property price
BUT the error is in the Invoice object NOT in the LineItems object therefore I cannot highlight in RED the form appropriately. (And field value remains at zero when displayed so message is somewhat meaningless to user)
I was thinking of using COMMAND object with String parameters and validating their numeric value but I can't figure how to bind the InvoiceItem List.
What is the appropriate Grails way?
I could do all validation on the client side in javascript but that is not my question
You can do it with command objects. You need to read:
http://blog.peterdelahunty.com/2009/01/cool-way-to-dynamically-add-entries-to.html
command object data binding
Grails command object data binding
http://grails.1312388.n4.nabble.com/validating-nested-command-objects-td1346994.html

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

What is the difference in behavior of [MaxLength] and [StringLength] attributes?
As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?
MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:
Specifies the maximum length of array
or string data allowed in a property.
StringLength is a data annotation that will be used for validation of user input.
From MSDN:
Specifies the minimum and maximum
length of characters that are allowed
in a data field.
Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Will output the following if it is over the character limit:
"Address can have a max of 100 characters"
The placeholders I am aware of are:
{0} = Property Name
{1} = Max Length
{2} = Min Length
Much thanks to bloudraak for initially pointing this out.
Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class
public class Student
{
public Student () {}
[Key]
[Column(Order=1)]
public int StudentKey { get; set; }
//[MaxLength(50),StringLength(60)] //studentname column will be nvarchar(50)
//[StringLength(60)] //studentname column will be nvarchar(60)
[MaxLength(50)] //studentname column will be nvarchar(50)
public string StudentName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.
One another point to note down is in MaxLength attribute you can only provide max required range not a min required range.
While in StringLength you can provide both.
MaxLengthAttribute means Max. length of array or string data allowed
StringLengthAttribute means Min. and max. length of characters that are allowed in a data field
Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/
You can use :
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
public string Address { get; set; }
The error message created by the preceding code would be "Address length must be between 6 and 8.".
MSDN: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0
I have resolved it by adding below line in my context:
modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);
Somehow, [MaxLength] didn't work for me.
When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.

How to get Pylons formencode validator to ignore some fields

I have a form that has some input text boxes and well as some select boxes. I have validation working perfectly on the textboxes. I don't care if any of the select boxes are left defualt or not, but everytime I submit the form it goes to a pylons error page saying "Invalid: Please enter value for ..." But I don't want that to happen.
here is my validator function:
class Registration(formencode.Schema):
allow_extra_fields=True
first_name = formencode.validators.String(strip=True, not_empty=True)
last_name = formencode.validators.String(strip=True, not_empty=True)
address = formencode.validators.String(strip=True, not_empty=True)
phone = formencode.validators.PhoneNumber(strip=True, not_empty=True)
email = formencode.validators.Email(resolve_domain=True, not_empty=True)
messages = {
'tooLow': "You must be at least 18 in order to register for an event.",
'tooHigh': "You obviously are not that old. Please enter your actual age.",
}
age = formencode.validators.Int(min=18, max=999, not_empty=True, messages=messages)
I thought with allow_extra_fields = True it would allow for fields in the form that aren't supplied in the function to pass if left blank/default. I have select boxes named heard, frequency, and level that should be ignored.
Any help here would be greatly appreciated.
On your formencode.validators methods:
Use not_empty=False if your form is submitting the fields and the values are empty strings. The param not_empty false is how you say: empty is a valid value.
If the fields do not exist then use if_missing = None which will set your result to None.
I think you should add the following line to it
filter_extra_fields = True

Resources