validation message is not showing in client side in mvc razor - asp.net-mvc-3

I am working on MVC Razor and I want to validate my model as per condition.
codtion is if IsDefaultMailingAddress is true then only DeliveryLine and Zip will be Required otherwise page is submitted.
I have searched so many artical and got below metion blog
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
and I have implemented Reqiuedif in my model which is mentioned below
my model:
RequiredIf("IsDefaultMailingAddress",true, ErrorMessage = "Must add DeliveryLine ")]
public string DeliveryLine { get; set; }
RequiredIf("IsDefaultMailingAddress",true, ErrorMessage = "Must add Zip")]
public string Zip { get; set; }
public bool IsDefaultMailingAddress { get; set; }
Everything is working fine but the Problem is when i click submit buttion it is going to server side and there model state isvalid
showing false.why before going to server it is not showing all error message
"Must add DeliveryLine and Must add Zip"
please let me know what what should be implement this client side validation.

You should have to enable ClinetValidation to get work around this. In the view just add the below html helper.
#Html.EnableClientValidation()

Related

MVC3 validate only one entity in ViewModel

I have an mvc3 create page using a View Model with 2 entities
like
class ViewModel1{
public User user{get;set;}
public Company company{get;set;}
}
where User and Company are EF4 entities(tables). I need to use a single page to create both(related) tables. Now the Company entity is optional under some conditions and I use jQuery to hide the corresponding section in the view.
However since company has required fields , the post back create function has ModelState.Valid as false.
What I want to do is if the Company section is hidden, I would like to skip validating the Company entity in ViewModel in Server( I avoid validation of hidden elements in Client).
Maybe there is a better and more proper approach to this?
What you have shown is not a view model. You call it a view model but it isn't because it is referencing your EF domain entities.
A more realistic view model would look like this:
class ViewModel1
{
public UserViewModel User { get;set; }
public CompanyViewModel Company { get; set; }
}
or even flattened out and containing only the properties that your view needs:
class ViewModel1
{
public int UserId { get;set; }
[Required]
public string FullUserName { get;set; }
[Required]
public string CompanyName { get; set; }
}
Now depending on your specific requirements about view model validation your UserViewModel and CompanyViewModel classes will be specifically designed for them.
Instead of putting the entities directly in the view model, put the properties for the entities in the view model and map between the view model and the actual entity objects on the server. That way you can control what properties are required for your view. Create some custom validation rules to validate that the required company properties are there when some company information is required. To do this on the server, you can have your view model implement IValidatableObject and implement the logic in the Validate method. On the client you can add rules to the jQuery validate plugin for the "required if" properties.
public class UserCreationViewModel : IValidatableObject
{
[Required]
public string Username { get; set; }
[Required]
public string FirstName { get; set; }
...
public string CompanyName { get; set; }
public string CompanyEmail { get; set; }
public IEnumerable<ValidationResult> Validate( ValidationContext context )
{
if (!string.IsNullOrEmpty(CompanyName) && string.IsNullOrEmpty(CompanyEmail))
{
return yield new ValidationResult("Company Email is required if you specify a company", new [] { "CompanyEmail" });
}
}
}
I'm not sure what I would do on the client-side. You have a choice of either adding specific rules to the validate plugin directly, but it might be hard to make it look exactly the same as using the unobtrusive validation that MVC adds. Alternatively, you could look at adding/removing the unobtrusive attributes from the "required if" elements using jQuery depending on the state of the elements that trigger their requirement. I suggest trying both ways -- look at the docs for the validate plugin to see how to add custom rules and examine the code emitted by the MVC framework for the unobtrusive validate to see what you would need to add to make that work.
Another possibility would be including/removing a partial view with the company properties in the from based on whether the company information is required or not. That is, type in a company name and use AJAX to grab the inputs required for the company and add them to the form. If the company name is deleted, delete the elements. Leave the server-side validation the way it is, but in the partial view mimic the HTML that the framework would add in for unobtrusive validation. This is sort of the best of both worlds as the jQuery code is much simpler and you get consistent validation, too.
There are many ways you can achieve,
1) more commonly donot use [Required] attribute on Company object, but have proper validation for parameters inside Company object.
In this case if Company object is null still validation will pass, but if Company object isnot null it will validate each properties.
2) If validation involves some complex business logic, then go for Self Validating Model. (inherit from IValiddatableObject, and override Validate(...).
3) By code, in the controller.
if(model.company == null)
this.ModelState.Keys.Where(k => k.Contains("company")).ToList().ForEach(k => this.ModelState.Remove(k));
first two are best approved approaches, third is just another way to achieve your functionalities

Display Friendly Error Message When Html tag is entered in a text Box- MVC ASP.NET

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.

RIA service default required attribute

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

How do I show a different Required message to instances of the same object in MVC3?

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

MVC 3, NHIbernate Validators & Message Interpolator

I have followed this article and have a passing test showing custom validation error messages being returned from a resource file when a call to Validator.IsValid(someEntity) fails.
I am trying to translate this to the new unobtrusive client-side validation in MVC3 describe by this article. This also more or less works - well the client-side validation does so I can assume my wiring of NHValidators is good, as you can see the following is output:
<input data-val="true" data-val-required="{NotNullNotEmpty}" id="Username" name="Username" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Username" data-valmsg-replace="true">
My problem is that this time the CustomMessageInterpolator has not fired - the resource string has not been translated for this property (it's still in curly braces): {NotNullNotEmpty}.
Both my test and the web are usign the same NHValidator config:
var cfg = new FluentConfiguration();
cfg
.SetMessageInterpolator<CustomMessageInterpolator>()
.SetCustomResourceManager("MyProject.Core.Resources.ValidationMessages", Assembly.Load("MyProject.Core"))
.SetDefaultValidatorMode(ValidatorMode.UseAttribute)
.Register(Assembly.Load("MyProject.Core").ValidationDefinitions())
Just for good measure here's the model snippet:
public class LoginModel
{
[NotNullNotEmpty(Message = "{NotNullNotEmpty}")]
public string Username { get; set; }
Long shot I know but any ideas would be appreciated!
I had no luck with this having posted it around a few forums.
In the end I've resorted to using DataAnnotations instead in my View Models for client-side validation.
Of course this is really hacky and a horrible "solution" as I've now two types of validation attributes in my code. (if wondering, yes I'd rather keep my NH Validation attributes 1. as I'm still generating my schema from them and 2. I like the way NH validates before committing to the db i.e. server-side).
If interested, here's how to use resource files to show the correct labels for your controls.
This code snippet shows how to then also rig up custom error messages:
[DisplayResource(typeof(LabelResources))]
public class NewChildTagViewModel : ModuleViewModel
{
public int ParentId { get; set; }
[Required]
public string Title { get; set; }
[Range(1, 1000, ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "Display_Order")]
[Required]
public int? DisplayOrder { get; set; }
}
Can you show your code? I presume you used some sort of custom ModelValidatorProvider?
I've got something working like what you described. It required writing a custom AssociatedValidatorProvider and ModelValidator, along the lines described here
http://weblogs.asp.net/srkirkland/archive/2010/07/20/nhibernate-client-validator-asp-net-mvc-2-model-validation.aspx
but changing the MessageOrDefault method in the article above to use the NHibernate Validator DefaultMessageInterpolator to translate the messages.
It sounds like you got most of the way towards getting something working, and you just needed to use the DefaultMessageInterpolator to translate the messages.

Resources