I have form on my website which is contact form. I am using ReCaptcha on that.
The form just sending email, no records to data base.
So my question is should i put character limit on that message?
It's always a good idea to put limits on input fields. For example you could decorate the property on your view model which is bound to the message with the StringLength attribute to enforce validation.
[StringLength(1000, ErrorMessage = "The message must be at most {1} characters long.")]
[AllowHtml]
public string Message { get; set; }
Related
I have requirement of validating user input in a text box. Whenever a html tag is entered it should display the same view with friendly error message like "Cannot enter html tags."
The ways I have tried so far are:
[ValidateInput(true)] on the Controller- It comes up with error "Potentially dangerous request"
[ValidateInput(false)] on the Controller- It stores the value in the database-(I don't want this)
In the view Model I placed a tag for the property [RegularExpression ( "<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>",ErrorMessage = "You have entered html…Html is not a valid input!" )]
any one had this this issue. If yes please let me know, how have you fixed that.
Thank you
You could use the [AllowHtml] attribute:
[AllowHtml]
[RegularExpression (#"^[^<>]*$", ErrorMessage = "You have entered html... Html is not a valid input!" )]
public string SomePropertyThatShouldNotAcceptHtml { get; set; }
Obviously before storing in the database you should ensure that the contents is safe:
[HttpPost]
public ActionResult Save(MyViewModel model)
{
if (!ModelState.IsValid)
{
// the model is invalid => redisplay view
return View(model);
}
// the model passed validation => store in the database
...
return RedirectToAction("Success");
}
And if you are afraid of XSS you could use the AntiXSS library which will filter out all the dangerous scripts from the HTML. You could even write a custom model binder which will perform this step and automatically assign only a safe HTML value to the property.
Good morning this looks like an excellent starting point to be able to handle your requirement. Check out this article.
It is working now by displaying the friendly error message. I have changed a little bit by adding Validateinput tag at the Post Action controller.
I have to add this in ViewModel
[AllowHtml]
[RegularExpression (#"^[^<>]*$", ErrorMessage = "You have entered html... Html is not a valid input!" )]
public string SomePropertyThatShouldNotAcceptHtml { get; set; }
In Action Controller
I have to add the tag in the Post Event
[Validateinput(false)]
Thanks Darin.
I'm getting odd behavior with my validation in my view.
My model has this property.
[Display(Name = "Overflow Capacity")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
public decimal OverFlowCapacity { get; set; }
My view has this:
<tr>
<td>#Html.LabelFor(m=> m.OverFlowCapacity)</td>
<td>#Html.EditorFor(m=>m.OverFlowCapacity)</td>
<td> #Html.ValidationMessageFor(model => model.OverFlowCapacity)</td>
</tr>
If I enter a value like 'ABC', I get the validation message 'Number required'
If I enter a value of 999999, I get the validation message 'Value must be between 0 - 9,999.99'
Both of those messages are received when I tab off the text box as expected.
When I leave the text box value empty and tab off, I get no errors, as expected.
However, when I submit, I get a validation message 'The Overflow Capacity field is required.'
I don't know where this is coming from. I've tried removing all validation attributes from the model, and still get the 'required' message. I'm at a loss.
Here are the scripts I've referenced.
I have other issues with mvcfoolproof that I may post later. I'm wondering if this isn't somehow responsible for my problems.
What's happening to you now is the post validation is kicking in after the form has been submitted and determining that the decimal value cannot be null. Right now you are using a decimal type which is non-nullable. If you want this behavior and you want to see the validation before you submit the form then add the [Required] attribute to the property. However if you don't want this functionality and it can possibly be null, then change your type from decimal to decimal? or Nullable<decimal>.
Don't allow nulls and have the pre-submit validation:
[Display(Name = "Overflow Capacity")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
[Required]
public decimal OverFlowCapacity { get; set; }
Allow nulls and get rid of post-submit validation error:
[Display(Name = "Overflow Capacity")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Number required.")]
[Range(0,9999.99,ErrorMessage = "Value must be between 0 - 9,999.99")]
public decimal? OverFlowCapacity { get; set; }
Since you're not marking your decimal type as nullable, MVC doesn't know what to do with the empty field you're posting back. Try this if you want to allow nulls/empty fields:
public decimal? OverFlowCapacity { get; set; }
and try this if you want it to have a pre-submit validation message requiring the field to be filled in:
[Required]
public decimal OverFlowCapacity { get; set; }
Answers above explain Required error message quite well so i will just focus on second error message. i.e if you put 'abc' jquery tells you "Number Required". How does jquery know that this input should only accept number fields. The answer is; through unobtrusive attributes that are generated with form fields. If you inspect input field you will find something like
<input name="OverFlowCapacity" id="OverFlowCapacity" data-val-number="Number Required"..../>
so to override this default validation message you have to decorate your model with the attribute that does the exact same thing (number validation) and their you can override the validation message
[Numeric(ErrorMessage="override message")]
[Required(ErrorMessage="override Required message")]
public decimal OverFlowCapacity{get;set;}
I doubt Numeric attribute is present in DataAnnotation or mvc framework. you have to check into that. There are some useful attributes discussed and available here
I am working on an ASP.Net MVC3 application and I'm having trouble understanding the "right way" to do the validation I'm looking for.
For example, consider a model that looks like this:
[Required]
[StringLength(10, MinimumLength = 10)]
[RegularExpression("[0-9]{10}")]
public string Id { get; set; }
[Required]
public string Value { get; set; }
If I have an Id of "2342" and try to POST back, the model mapping kicks in and registers an error because of the length validation. However, if perform a GET against /controller/2342, then MVC seems to happily create a model with this invalid state (ModelState.Valid will be true). I could create some validations in the controller to catch this, but it seems redundant.
What is the best way to do this?
Thanks!
Jacob
When you perform a GET, you are simply retrieving a model with a given ID. So there is no validation performed. If you really want to make sure that requested model IDs should be 10 numbers in length, you should define constraint in Global.asax:
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = #"[0-9]{10}" }
);
There is nothing in the framework that by default validates a model on a GET request as validation isn't generally required at that time. If you do want to force a validation here, this was answered in this prior question
See:
Validate model on initial request
In my model I have the following property:
[DataType(DataType.Currency)]
public decimal? Budget { get; set; }
When the user enters in $1,200.34, I need that value to be valid and strip out the currency symbol and comma.
In my controller I'm doing:
if (race.Budget != null)
{
race.Budget.ToString().Replace("$", "").Replace(",", "");
}
The problem is that client validation doesn't pass the value for budget into the controller. I get a value of null. How can I override the client validation so that I can strip out the currency symbol and comma?
Thank you in advance for the help.
UPDATE
So here's the strange thing. Let's say I want to bypass client validation all together. I added #{ Html.EnableClientValidation(false); } to my view and it's still sending a null value for Budget when I submit to the controller.
This isn't a client side validation problem. Your model has a field of type decimal? The model binder will try to bind a value of $123,456.78 into that and fail, so the value will be null. Here's one way to get around this:
Change your model to have a string property that masks your decimal:
public decimal? Budget { get; set; }
public string BudgetText {
get {
return Budget.HasValue ? Budget.ToString("$") : string.Empty;
}
set {
// parse "value" and try to put it into Budget
}
}
Then, just bind to BudgetText from your View. Validate it as a string with a regular expression that accepts only money input. It'll probably be the same regex you can use for your BudgetText's set method
So you can probably hook in some JQuery to pre-process the form field to strip the characters off you don't want (prior to form submission to the server). This is probably the quickest, dirtiest approach.
For something reusable, have a look into custom client validation adapters. The links aren't spot on, but should get you in the right direction. For Brad's screencast, I believe the relevant parts are fairly early on.
Check out the support for jQuery localization
cliente validation using jQuery validate for currency fields
also there is a plugin for currency validation as well
http://code.google.com/p/jquery-formatcurrency/
check out this recent post as well for a $ in binding
.NET MVC 3 Custom Decimal? Model Binder
How do I pass a value from Membership Provider (taken from web.config) to Validation Attributes in AccountModels in default MVC 3 project?
Membership.MinRequiredPasswordLength
returns value obtained from web.config and Register.cshtml view uses it:
<p>
Passwords are required to be a minimum of #Membership.MinRequiredPasswordLength
characters in length.
</p>
But it seems that ViewModel in AccountModels file have the values hard-coded in:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
So how do I pass the value from web.config to MinimumLength parameter?
You won't be able to specify an attribute property dynamically like you would like. That is why the templates have it hard-coded. The workaround to still use data annotations would be to have your view model implement IValidatableObject and have it check the password against Membership.MinRequiredPasswordLength. Another option would be to create an attribute that inherits from ValidationAttribute and checks against Membership.MinRequiredPasswordLength.
David Hayden has a post covering both of these options.
For the client side, you would need to implement IClientValidatable on the model or the custom attribute. Here is another answer that shows an example. You would also need to add the client side validation function, and you could use #Membership.MinRequiredPasswordLength inside your Razor view to pull in the value.