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.
Related
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()
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.
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 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