Display required attribute message as html text in mvc3 - asp.net-mvc-3

I has required field like this
[Required(ErrorMessageResourceName = "AddCategoryCodeRequiredError", ErrorMessageResourceType = typeof(Resources.Category.Category))]
public string CategoryCode { get; set; }
and the error message in the resource file like this
<b>Required Field Missing</b> A code is required.
when the error displayed in the page the message part
<b>Required Field Missing</b>
displayed as is not as bold text.
how can I display the message as html??

The Html.ValidationSummary helper is designed to HTML encode the error message. This basically means that you cannot use HTML tags inside your error messages. If you wanted to do so you will have to write a custom helper to display it which doesn't perform encoding. Here's an example with a custom validation summary helper. The same is true for the ValidationMessageFor helpers.

Related

DropdownList Data Annotation does not fire when the Textboxes and other controls are firing

I have a form that has several controls in it. I added data annotation to display an error message to the user when the required field are left empty. The TextBoxes and other controls display the message, which is an "*" before the label name, but the dropdownlist does not not. Once the user get rid of all the error messages and click on submit again, then, the message for the dropdown box is display. How do I force the dropdown box to display the message at the same time with the textbox?
Additional information:
Here is a sample of my data annotation:
[MetadataType(typeof(UserMetaData))]
public partial class UserMeta
{
}
public class UserMetaData
{
[Required(ErrorMessage = "*")]
public int GenderID { get; set; }
//The gender ID is displayed in a dropdown
list with "Select" as the default option. Then, it has all the other genders
showing in the dropdown once it is clicked on.
[Required(ErrorMessage = "*")]
public DateTime DataOfBirth{ get; set; }
}
In my view, I am using
#Html.ValidationMessageFor(model => model.DataOfBirth) //This is working fine.
#Html.ValidationMessageFor(model => model.GenderID)
//Here is the dropdown
#Html.DropDownList("GenderID", null, "Select", new { style = "width:200px;", onchange = "ValidateDropdown()" })
//This is the one that is not working as expected. I could get it to work using javascript, but I am trying not to it if I there is a way to get it to work properly using data annotation.
Thank in advance for your help.
I could not get it to work properly on the server side. As a result, I had to write a JQuery function that does the validation for the dropdown on the client side. Then, I do the post only if there is a selection on the dropdown.

Asp.net MVC Html.TextboxFor title and validation message conflict

I have a Asp.net MVC application(using Razor View) in which i am using Html.Textboxfor for textbox. Below is the code :
#Html.TextBoxFor(m => m.Textbox1, Model.Attributes)
The attributes i am adding for these are
Model.Attributes = new Dictionary<string,object>);
Model.Attributes .Add("size", "3");
Model.Attributes .Add("min", 0);
Model.Attributes .Add("max", 100);
Model.Attributes .Add("title", "Value");
So when i click on submit i am validating the Textbox and it shows the default title as error message when data outside the specified range is entered. Any way to prevent this from happening and add a custom error message different from title?
im not sure what u try to do but i think u need just use data anotation
[StringLength(100, MinimumLength=1, ErrorMessage = "error message here")]
public string title { get; set; }

Link in validation summary message

Is it possible to put a HTML link in validation summary message? For example I want to put a link to another page in case there is validation error:
#Html.ValidationSummary(False, "read more")
or
#Html.ValidationSummary(False, "read " &
Html.ActionLink("more", "helpforerror").ToHtmlString)
But in the browser the tag is escaped so it doesn't form a link.
I know you have accepted an answer, but i think my solution is more simple and will require less rewriting if you want to add links to existing validation summaries.
You need to put a {0} type format item in your validation message like below, which will be replaced by your link.
ModelState.AddModelError("", "Some error message with a link here {0}.");
then in your view call your validation summary like so:
#string.Format(Html.ValidationSummary().ToString(), Html.ActionLink("Click Here", "Action_To_Link_To")).ToHtmlString()
In this case i have used an extension method I added to the string object .ToHtmlString() that basically just converts the string to an HtmlString preventing any of the markup being escaped. it looks like this:
public static HtmlString ToHtmlString(this String str)
{
return new HtmlString(str);
}
Finally I chose another way to do it: create a div containing the link etc. outside of validation summary, and add the div only if modelstate is not valid:
#If Not ViewData.ModelState.IsValid Then
#<div>read more</div>
End If
This is inspired by an answer to similar question.
The validation text is encoded before the ValidationSumary or ValidationFor, etc...
you just need tu decode the html, then create an MvcHtmlString ...
Exemple :
#HttpUtility.HtmlDecode(Html.ValidationSummary().ToString()).ToMvcHtmlString()
this is an extension i have made to make MvcHtmlString :
namespace System
{
public static class StringExtension
{
public static System.Web.Mvc.MvcHtmlString ToMvcHtmlString(this string value)
{
return System.Web.Mvc.MvcHtmlString.Create(value);
}
}
}
or you can create an HtmlHelper if you plan to reuse this:
namespace System.Web.Mvc.Html
{
public static class FormHelper
{
public static MvcHtmlString ValidationSummaryEx(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var original = htmlHelper.ValidationSummary(excludePropertyErrors);
var decoded = HttpUtility.HtmlDecode(original.ToString());
return decoded.ToMvcHtmlString();
}
}
}
Hope it help you or future viewer.
Note: it work for all validations Summary and ValidationFor ...
No, the default behaviour doesn't allow it, but you can make your own. This is what you need: Html raw in validationsummary
You can check if form is valid by jquery and update div with link text:
<div id="divToUpdate">
</div>
$('form').submit(function(){
if(!this.valid())
$('#divToUpdate').html("read <a href='anotherpage.html'>more</a>");
});
If you're sending back HTML in the ModelStateError, you can use this one liner:
#Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary().ToHtmlString()))
It's very similar to what #Benoit had suggested, just without needing the extension.

how to restrict HTML elements while allowing others

How to only allow certain html tags in a text box
Example:
<Strong>
<p>
The code below is where I have been trying to implement the solution in a class created.
[Required]
(Code)
Public string car { get; set; }
How would I go about implementing the solution and is it possible at the point where (code) is written above.
First, you would need to disable the validation for you action with [ValidateInput(false)] attribute but you will need to use that carefully as it will turn off validation for the whole method. You may also disable validation for a particular attribute like :
[Required]
[AllowHtml]
Public string article { get; set; }
ASP.NET MVC3 has built-in attribute to disable validation at property level - so putting [AllowHtml] attribute on properties in model or view model will disable request validation. This is not safe and puts your site at risk. Now it's up to you to ensure that proper data format is provided so you may wan't to give a try a with Regular Expressions to filter out all html code except for the tags you need. You may wan't to take a look at this answer Regex to match all HTML tags except <p> and </p> to get you going.
example from msdn on how to use regex validation with data annotations :
public class Customer
{
[Required]
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$",
ErrorMessage="Numbers and special characters are not allowed in the last name.")]
public string LastName { get; set; }
}
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.95).aspx
you may also try the safer way - to implement BBCode like feature. So instead of html tags you use pseudo html tags like [b] instead of < b >
this is easy to accomplish with jQuery :
assuming #text is a field populated with bbcode like text (not visible) and text2 is formatted display - visible :
$(document).ready(function(){
var text = $('#text').html();
text = text.replace("[b]","<b>");
text = text.replace("[/b]","</b>");
$('#text2').html(text);
});
it's not the smartest code but it was a quick one to show you a direction you can take.
The following Regular Expression allows only the Html tags specified:
[RegularExpression(#"^([^<]|<p>|</p>|<strong>|</strong>|a z|A Z|1 9|(.\.))*$")}
This allows for the html <p> </p> <strong> </strong> to be entered while not allowing any other tags.
Add other tags if required.
use AllowHtml attribute and then validate the content using IValidatableObject and Regex,
or write a custom validation attribute to allow only some html tags with Regex, see Phil Haack article http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
[RegularExpression("^[^<>,<|>]+$", ErrorMessage = "Invalid entry.")]
public string FirstName { get; set; }
To avoid mvc error.

MVC 3 - Change Html.TextBox to Html.TextBoxFor

I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor.
However, I realise i need to have the textboxfor for the validation in my model class to work:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??
#Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
#Html.ValidationMessageFor(model => model.ExpiryDate)
Appreciate any help... Thanks...
You don't really need to use TextBoxFor() for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.
However, in this case it sounds like what you really want is a custom editor, using EditorFor(). It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:
Create a partial view called DateTime.cshtml that is bound to model of type Nullable<DateTime>, and put it into the Shared/EditorTemplates view folder.
Use jQuery and jQueryUI to put an HTML textbox that is styled as a date/time picker into the partial view.
Decorate the property on your model with the [DataType(DataType.DateTime)] attribute
Use Html.EditorFor(model => model.WhateverProperty)
Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:
#inherits System.Web.Mvc.WebViewPage<System.DateTime>
with this:
#model System.DateTime?

Resources