How to validate that user enters string in textbox in asp mvc4 - asp.net-mvc

How to validate that user enters string in textbox in asp mvc4?
What to write in required tag?
[required]

Use the [RegularExpression] attribute if you want to limit the user to only typing in alphabetic characters.
More info on MSDN.
Here is a good link to a regular expression that you can use.

This example maybe helps:
public class CustomerMetaData
{
// Require that the Title is not null.
// Use custom validation error.
[Required(ErrorMessage = "Title is required.")]
public object Title;
// Require that the MiddleName is not null.
// Use standard validation error.
[Required()]
public object MiddleName;
}

There are many ways to do it
1) By using plain Javascript or JQuery to check if it has value before submiting the page
2) On controller method check if it has value
3) If you a using EF and your view binded to a model add attribute called [Required]to the property of that model.

What do you actually want to do?
Make sure that the object the server receives has correct data in it? Then you should use data attributes on your C# model. However what do you mean by "enters string"? If the user simply needs to enter any string, then [Required] works - this just means that there has to be some value entered. Do you only want to allow a specific set of characters, like the English alphabet? Then you need to use a RegularExpression attribute.
If you further specify what you actually want to do I am sure we can help you more.

Related

Friendly Way to Handle Potentially Dangerous Values

I'm after a friendly way to handle A potentially dangerous Request.Form value was detected
I want to be able to validate it myself and return my own validation message.
I was thinking of using the [AllowHtml] attribute then checking to see if the value contains potentially dangerous content via another ValidateAttribute or using IValidatableObject.
Is there a built in helper to manually validate the property's value?
Is there a better way of doing what I'm trying to achive?
Why not use [AllowHtml] together with another validation like that:
[AllowHtml]
[RegularExpression("(\<[a-zA-Z\!\/\?]|&#|script\s*\:)", ErrorMessage = "Invalid characters or whatever your message is")]
public string Description { get; set; }
See Security Extensibility in MVC4 document for more info. Hope it helps!

MVC 5 - change Data anotation error message for Integers

In my Mvc5 test project I have a model with a property like the following:
[Required]
[DisplayName("Codigo Cliente")]
public int ClientCode{ get; set; }
the default error message when the user enteres a letter of special character in the editor is:
The field Codigo Cliente must be a number.
How can I modify this? in this case I need to change the language, but in case that I wanted to show a more specific error what can I do?
I have tried with the DataType attribute but the Enum does not have a value that applys for this case (numbers)
Use Range:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx
Or use IntegerOnly from Data Annotations Extensions
http://dataannotationsextensions.org/Integer/Create
The simplest way I found to solve this issue is use String with Range attribute in Data Annotation Model like specify below.
[Required]
[Range(0, int.MaxValue, ErrorMessage = "Codigo Cliente must be a positive or negative non-decimal number.")]
[DisplayName("Codigo Cliente")]
public string ClientCode { get; set; }
In Range attribute you can specify your custom Error Message.
For Interger use int.MaxValue , For double use double.MaxValue like so on.
I hope this will help you a lot.
If you want to specify a message you must use this
[Required(ErrorMessage = "your message")]
If you want to use a lang. based message is not that easy. You can use multiple resource file (for every language you need) and try a custom error binder that extends the DefaultModelBinder and make an override of the method BindModel(), there you can make your custom validation ad use your custom language message.

How can I validate an email address using the same method used by the DataAnnotations attribute DataType.EmailAddress?

I am using MVC3 and in certain locations in the code I am using the System.ComponentModel.DataAnnotations.DataType.EmailAddress attribute and letting MVCs Model validation do the validation for me.
However, I would now like to validate an email address in a different section of code where I am not using a model. I would like to use the same method that is already being used by MVC, however I was unable to find any information on how to do so.
EDIT - Sorry if my question was unclear. I will attempt to clarify.
Here is a snippet from the RegisterModel that is included with the default MVC template:
public class RegisterModel
{
...
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }
...
}
These attributes instruct mvcs model validation on how to validate this model.
However, I have a string that should contain an email address. I would like to validate the email address the same way that mvc is doing it.
string email = "noone#nowhere.com";
bool isValid = SomeMethodForValidatingTheEmailAddressTheSameWayMVCDoes(email);
As others have said, the DataType attribute doesn't actually do any validation. I would recommend you to look at Data Annotations Extensions which includes already written validation extensions for a variety of things, including Email.
It is also possible to do model validation on your full model explicitly: Manual Validation with Data Annotations.
If you want to do per attribute validation for a specific field/property, you can also look at the tests for DataAnnotationExtensions which should give you what you want:
[TestMethod]
public void IsValidTests()
{
var attribute = new EmailAttribute();
Assert.IsTrue(attribute.IsValid(null)); // Don't check for required
Assert.IsTrue(attribute.IsValid("foo#bar.com"));
..
}
Have a look at this blog post by Scott Guthrie, which shows how to implement validation of an email address using a custom attribute (based on the RegularExpressionAttribute).
You can reuse that logic if you need to validate the email address somewhere else.
You may want to look at this question: Is the DataTypeAttribute validation working in MVC2?
To summarize, [DataType(DataType.EmailAddress)] doesn't actually validate anything, it just says "hey, this property is supposed to be an e-mail address". Methods like Html.DisplayFor() will check for this and render it as foo, but the IsValid() method is pretty much a simple return true;.
You'll have to roll your own code to actually perform validation. The question linked above has some sample code you can use as a starting point.

asp.net mvc 3 validation on data type

I am trying to realize valition on data type. I have used DataAnnotations, but for data type it's not showing customized message
for example when I' am trying enter string data into int typed field. How I can customize messages in this case?
If I had to guess, you sound like you want a custom message to display when validating one or more fields in your model. You can subclass the DataAnnotations.ValidationAttribute class and override the IsValid(object) method and finally setting a custom ErrorMessage value (where ErrorMessage already belongs to the ValidationAttribute class)
public class SuperDuperValidator : ValidationAttribute
{
public override bool IsValid(object value)
{
bool valid = false;
// do your validation logic here
return valid;
}
}
Finally, decorate your model property with the attribute
public class MyClass
{
[SuperDuperValidator(ErrorMessage="Something is wrong with MyInt")]
public int MyInt { get; set; }
}
If you're using out-of-the-box MVC3, this should be all you need to propertly validate a model (though your model will probably differ/have more properties, etc) So, in your [HttpPost] controller action, MVC will automagically bind MyClass and you will be able to use ModelState.IsValid to determine whether or not the posted data is, in fact, valid.
Pavel,
The DataAnnotations DataType attribute does not affect validation. It's used to decide how your input is rendered. In such a case, David's solution above works.
However, if you want to use only the built-in validation attributes, you probably need to use the Range attribute like this:
[Range(0, 10, ErrorMessage="Please enter a number between 0 and 10")]
public int MyInt { get ; set ;}
(Of course, you should really be using the ErrorMessageResourceName/Type parameters and extract out hard-coded error message strings into resx files.)
Make sure to let MVC know where to render your error message:
<%= Html.ValidationMessageFor(m => m.MyInt) %>
Or you can just use EditorForModel and it will set it up correctly.
I don't think this has been answered because I have the same issue.
If you have a Model with a property of type int and the user types in a string of "asd" then the MVC3 framework binding/validation steps in and results in your view displaying "The value 'asd' is not valid for <model property name or DisplayName here>".
To me the poster is asking can this message that the MVC3 framework is outputting be customized?
I'd like to know too. Whilst the message is not too bad if you label your field something that easily indicates an number is expected you might still want to include additional reasons so it says something like:
"The value 'asd' is not valid for <fieldname>; must be a positive whole number."
So that the user is not entering value after value and getting different error messages each time.

Asp.NET MVC Custom Validator For a View Model?

I am using custom view model classes as DTO objects to hold data for display on my View pages. I have applied validation via the DataAnnotations library to perform server side validation on the properties of these classes. Here is a simple example:
[DisplayName("Customer Account Id")]
[Required(ErrorMessage = "* Account Number is required")]
[StringLength(16, ErrorMessage = "* Account Number must be 16 characters in length", MinimumLength = 16)]
public string CustomerAccountId { get; set; }
If someone submits a search and this field does not come through or comes through at a length that is not 16, validation fails, and an error message is displayed on the page via the ValidationMessage HtmlHelper:
<%= Html.ValidationMessage("CustomerAccountId")%>
Now I need to add the ability to search by account id OR a combination of First/Last name. My question is this:
How do I apply conditional validation? If I submit a search with First/Last name, I don't want validation to fail because an account number was not passed through as well. I found this link, which shows how to implement a custom validator, but it seems like this applies to 1 property. How do I pass an entire object model through, and pass back the appropriate validation error messages to the appropriate fields to be displayed on the page? Is this possible?
You can implement IDataErrorInfo. (The class name is misspelled in the article title, but the code is right.)

Resources