enterprise library VAB Implementation issues - asp.net-mvc

I have an issue with the implementation of VAB. We are using ASP.NET MVC 1.0
I have a property "First Name" and we want to have 2 validations.
Not Null Validator
RegEx Validator (to stop some characters)
Now if I leave it blank then it gives me the error message from both the validator.
If the First name is blank I only want Not Null to show the error details
If the First name is not blank then i was the RegEx to get executed and if there are any invalid characters then i want to stop them.
Please guide me here
Thanks !

The Not Null Validator is not going to pick it up because the string is not null - it is an empty string. Have a look at this post: http://geekswithblogs.net/michelotti/archive/2008/06/12/122836.aspx

When you're using Enterprise Library 5.0, you can mix VAB attributes and DataAnnotation attributes (because VAB now extends DataAnnotations). When you decorate your property as follows, your problem is solved:
[System.ComponentModel.DataAnnotations.Required]
[EnterpriseLibrary.Validation.Validators.RegexValidator("...")]
public string LastName { get; set; }

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!

Custom Validation on Multiple Inputs in ASP.net MVC

After researching various methods to implement custom form validation rules in MVC I have found, what I originally considered to be a straightforward bit of validation, to be rather more complex that I anticipated.
I have 2 text inputs, one or the other (or both) need to be populated. If both are NullOrEmpty we need to throw an error.
I have found DataAnnotations to have it's limitations when attempting to validate on multiple fields, giving me highlighting on both inputs and throwing a single error. Is this some beginners naivity?
I also played around with FluentValidation and was unable to get the results I was after.
Currently I am throwing the error in the Controller using:
ModelState.AddModelError("PropertyName", "You need to enter a Property Number or a Property Name")
ModelState.AddModelError("PropertyNumber", String.Empty)
This gives me highlighting on both fields and server-side validation. I am now finding it difficult binding custom client-side validation without using DataAnnotations.
Does anyone have any advice on how to do this properly? Any help or suggestions would be greatly appreciated. I need validation on the server/client, on both fields, with highlighting and a single error message.
Thanks in advance.
[Fool proof][1] validation library covers almost all kind of validation scenarios.
[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
Applied to a Model:
public class CreateUserViewModel
{
[Required]
public string Username { get; set; }
[Required]
public string Department { get; set; }
[RequiredIfEmpty(ErrorMessage="error message"]
public string Role { get; set; }
}

How to validate that user enters string in textbox in asp mvc4

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.

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.

How to use RegularExpression DataAnnotation with Resource file

I am currently using MVC 1.0 and .NET 3.5. I am using DataAnnotations to validate my model. I'm trying to add use the RegularExpression to validate a Postcode. I have stored my Regex in the resource file as many models will use it, when I try the following:
[RegularExpression(Resources.RegexPostcode, ErrorMessage="Postcode format invalid")]
public string Postcode { get; set; }
I get the following error when I build:
An attribute argument must be a
constant expression, typeof expression
or array creation expression of an
attribute parameter type.
Is there any way to use values from a Resource file as the regex or will I need to enter the actual regex string into every model that has a postcode?
Thanks
I would suggest making your own ValidationAttribute. This will keep the regex in one place as well as the error message.
class PostcodeAttribute : RegularExpressionAttribute
{
public PostcodeAttribute() : base("your regex")
{
this.ErrorMessage = "Postcode format invalid";
}
}
Can't leave a comment on the accepted answer as I don't have enough rep.
This accepted answer worked for me, but needed a tweak to work with the unobtrusive javascript validation. Needed the IClientValidatable bits from this answer: https://stackoverflow.com/a/18041534/1714585

Resources