I am having a problem with remote validation.
I have a viewmodel with a property on which I have added a Remote validator but when I run the form and enter a string in the text box the value passed to the controller is null.
The property in the viewmodel looks like this:
[Required(ErrorMessage = "Enter the host's name")]
[Remote("ValidateHostFullName", "BoardroomBooking", ErrorMessage = "Enter a different name")]
[DisplayName("Host's Name")]
public string HostFullName { get; set; }
The code for the validator in the Controller looks like this:
public ActionResult ValidateHostFullName([Bind(Prefix="BookingReceptionViewModel")]string HostFullName)
{
if (!HostFullName.Equals("John Smith"))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("{0} is not allowed", JsonRequestBehavior.AllowGet);
}
The value of the string for HostFullName shows as null no matter what is typed in the box. I have tried it with and without the Bind Prefix and that makes no difference.
I've tried this on a model and it works, it only seems to have an issue when I use a viewmodel.
Thanks
Mark
I was having the same issue. The parameter coming into ValidateHostFullName() must be the same as the input name.
I had the same problem. The rendered html control was NOT prefixed by class name but in remote validation code, I had binded by prefixing the classname.propertyname. Removing this binding solved my problem. Or else by prefixing only property name also works fine for me.
Related
My model contains a string field called "longdescription" which gets the value of the tinymce editor's content
Public class ArticleModel:BaseModel{
[StringLength(8000, ErrorMessage = "Long description must be in 8000 characters or less"), AllowHtml]
public string LongDescription { get; set; }
}
Here is my controller code
[HttpPost]
public ActionResult AddEdit(ArticleModel model)
{
string buttonName = Request.Form["Button"];
if (buttonName == "Cancel")
return RedirectToAction("Index");
// something failed
if (!ModelState.IsValid)
{
}
// Update the articles
}
My problem is when I use Request.Form to access the post value, it's working fine without throwing "A potentially dangerous...." error, but when I use Request.Params["Button"], it threw that errors. Is something I am missing?
Thanks
Updated
Sorry the answer Adam gave doesn't really answer my question. Can anyone give more suggestion?
Ideally you shouldn't really be using either. Those are more Web Forms centric values even though they 'can' be used.
Either pass in a FormsCollection item and check it there using collection["Button"] or even better - your cancel button itself should probably just do the redirect. Why post when you do nothing but redirect?
In your view you can emit the url via Url.Action() and put that into your button's click handler (client side)
It is the HttpRequest.Params getter that is throwing this exception. This getter basically builds and returns a key/value pair collection which is the aggregation of the QueryString, Form, Cookies and ServerVariables collections in that order. Now what is important is that when you use this getter it will always perform request validation and this no matter whether you used the [AllowHtml] attribute on some model property or if you decorated the controller action with the [ValidateInput(false)] attribute and disabled all input validation.
So this is not really a bug in the AllowHtml attribute. It is how the Params property is designed.
As #Adam mentioned in his answer you should avoid accessing request values manually. You should use value providers which take into account things such as disabled request validation for some fields.
So simply add another property to your view model:
public class ArticleModel: BaseModel
{
[StringLength(8000, ErrorMessage = "Long description must be in 8000 characters or less")]
[AllowHtml]
public string LongDescription { get; set; }
public string Button { get; set; }
}
and then in your controller action:
[HttpPost]
public ActionResult AddEdit(ArticleModel model)
{
string buttonName = model.Button;
if (buttonName == "Cancel")
{
return RedirectToAction("Index");
}
// something failed
if (!ModelState.IsValid)
{
}
// Update the articles
}
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 have an EF4 model with table's columns doesn't allow null.
At the SL client application I always receieve the "columnName is required" because I have the binding in xaml with [NotifyOnValidationError=True,ValidatesOnExceptions=True] for the textboxes.
My questions is:
I can overide the default required errormessage at the metadata class, but how can I have it as a custom validation? I mean I don't wnat to do this at the sealed metadata class:
[Required(ErrorMessage = "Coin English Name Is required")]
[CustomValidation(typeof (CustomCoinVaidation), "ValidateCoinName")]
public string coin_name_1 { get; set; }
I want to have it inside the custom validation method that I will define for all types of errors regards that coin_name_1, as follows:
public static ValidationResult ValidateCoinName(string name, ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(name))
{
return new ValidationResult("The Coin Name should be specified", new [] { "Coin Name" });
}
return ValidationResult.Success;
}
Why?
for two reasons :
1- Group all the validation isdie one container (for easy localization further).
2- I don't want the coin_name_1 to be displayed to the end-user, but a meanigful as "Coin English Name".
Second question:
I have a ValidationSummary control on my xaml page where all the errors are displayed but is displaying the orignal name of the column "coin_name_1" how can I chnge that to be a meanigfil also.
Best regards
Waleed
A1:
I just left the required as it is implemented right now..
A2:
I went through different sources and find this artical.
It shows how to style the validation summary:
http://www.ditran.net/common-things-you-want-know-about-silverlight-validationsummary
I am also implementing a client-side validation asyncronizly.
Regards
I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;
public class User
{
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
}
Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.
Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.
This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.
Ryan
One way you can accomplish this is with a separate view model for this screen, instead of a single User model with all the error messages. In the new view model, you could have a BackupContactFirstName property, KeyContactFirstName property, etc each with its separate error message. (Alternatively this view model could contain separate User models as properties, but I've found that Microsoft's client validation doesn't play well with complex models and prefers flat properties).
Your view model would look like this:
public class MySpecialScreenViewModel
{
[Required(ErrorMessage = "Backup contact first name is required")]
public string BackupContactFirstName { get; set; }
[Required(ErrorMessage = "Key contact first name is required")]
public string KeyContactFirstName { get; set; }
}
Then pass your view model to the view like this:
#model MySpecialScreenViewModel
...
Your post controller action would collect the properties from the view model (or map them to separate User models) and pass them to the appropriate data processing methods.
An alternative I have stumbled across, just modify the ModelState collection. It will have the elements in a collection named by index, like 'User_0__EmailAddress' and you can adjust / amend / replace the Errors collection associated with that key.
[Required(ErrorMessage = "{0} is required")]
{0}=The DisplayName is automatically placed on it
sample
[DisplayName("Amount per square meter")]
[Required(ErrorMessage = "{0} is required")]
public int PriceMeter { get; set; }
output
Amount per square meter is required
I am use DataAnnotations validation, it work perfectly but when I validate empty text box field I have error
The value '' is invalid
how can I customize this error?
p.s.
error shows only when clients script are off
You can specify the error message in your DataAnnotations attribute. For example, take the following view model:
public class ViewModel
{
[Required(ErrorMessage = "You must enter a name")]
public string Name { get; set; }
}
When that gets validated, it will give "You must enter a name" as the error message to the user.