how to make validation for special symbols ? - asp.net-mvc-3

I am developing MVC application.
In the application there is a mobile field.
I want to allow Numbers and +,-,(,) characters to be inserted.
How to write the validation for this ?
Right now I have only below code.
[StringLength(15, ErrorMessage = "Mobile can accept maximum 15 characters.")]
public string Mobile { get; set; }

Use a regular expression validator.
[RegularExpression(#"Pattern", ErrorMessage = "Error Message")]

Something like
^[\+\-\(\)0-9]{10,15}$
Should do the trick.
Use that pattern with the RegularExpression Attribute
Regards
Si

Related

MVC3 How To Phone Validation for model structure?

In my model structure PhoneNumber is not required but if user want to enter a value, it must be entered 10 digits.
I tried
[StringLength(10, MinimumLength = 10, ErrorMessage = "Girdiğiniz numara 10 karakter uzunluğunda olmalı")]
but it doesn't allow empty entry.
Is there anyone have an idea?
Use the Regular Expression Validator and then find/write a regular expression that validates the phone number. For example in the USA:
public class MyRegularExpressions
{
public const string USPhone = #"^[2-9]\\d{2}-\\d{3}-\\d{4}$|^[2-9]\\d{2}\\d{3}\\d{4}$";
}
And then the Atribute used in your model is:
[RegularExpression(MyRegularExpressions.USPhone)]
public string PhoneNumber { get; set; }
This way it is not required but when something is entered it has to match the specified regular expression.
If you need to write your own regular expression one of the best sites out there is: http://www.regexr.com/

Contact form. Message limit

I have form on my website which is contact form. I am using ReCaptcha on that.
The form just sending email, no records to data base.
So my question is should i put character limit on that message?
It's always a good idea to put limits on input fields. For example you could decorate the property on your view model which is bound to the message with the StringLength attribute to enforce validation.
[StringLength(1000, ErrorMessage = "The message must be at most {1} characters long.")]
[AllowHtml]
public string Message { get; set; }

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

.NET MVC3 Remove Currency Symbol and Commas

In my model I have the following property:
[DataType(DataType.Currency)]
public decimal? Budget { get; set; }
When the user enters in $1,200.34, I need that value to be valid and strip out the currency symbol and comma.
In my controller I'm doing:
if (race.Budget != null)
{
race.Budget.ToString().Replace("$", "").Replace(",", "");
}
The problem is that client validation doesn't pass the value for budget into the controller. I get a value of null. How can I override the client validation so that I can strip out the currency symbol and comma?
Thank you in advance for the help.
UPDATE
So here's the strange thing. Let's say I want to bypass client validation all together. I added #{ Html.EnableClientValidation(false); } to my view and it's still sending a null value for Budget when I submit to the controller.
This isn't a client side validation problem. Your model has a field of type decimal? The model binder will try to bind a value of $123,456.78 into that and fail, so the value will be null. Here's one way to get around this:
Change your model to have a string property that masks your decimal:
public decimal? Budget { get; set; }
public string BudgetText {
get {
return Budget.HasValue ? Budget.ToString("$") : string.Empty;
}
set {
// parse "value" and try to put it into Budget
}
}
Then, just bind to BudgetText from your View. Validate it as a string with a regular expression that accepts only money input. It'll probably be the same regex you can use for your BudgetText's set method
So you can probably hook in some JQuery to pre-process the form field to strip the characters off you don't want (prior to form submission to the server). This is probably the quickest, dirtiest approach.
For something reusable, have a look into custom client validation adapters. The links aren't spot on, but should get you in the right direction. For Brad's screencast, I believe the relevant parts are fairly early on.
Check out the support for jQuery localization
cliente validation using jQuery validate for currency fields
also there is a plugin for currency validation as well
http://code.google.com/p/jquery-formatcurrency/
check out this recent post as well for a $ in binding
.NET MVC 3 Custom Decimal? Model Binder

StringLength attribute, client side validation and a membership provider

How do I pass a value from Membership Provider (taken from web.config) to Validation Attributes in AccountModels in default MVC 3 project?
Membership.MinRequiredPasswordLength
returns value obtained from web.config and Register.cshtml view uses it:
<p>
Passwords are required to be a minimum of #Membership.MinRequiredPasswordLength
characters in length.
</p>
But it seems that ViewModel in AccountModels file have the values hard-coded in:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
So how do I pass the value from web.config to MinimumLength parameter?
You won't be able to specify an attribute property dynamically like you would like. That is why the templates have it hard-coded. The workaround to still use data annotations would be to have your view model implement IValidatableObject and have it check the password against Membership.MinRequiredPasswordLength. Another option would be to create an attribute that inherits from ValidationAttribute and checks against Membership.MinRequiredPasswordLength.
David Hayden has a post covering both of these options.
For the client side, you would need to implement IClientValidatable on the model or the custom attribute. Here is another answer that shows an example. You would also need to add the client side validation function, and you could use #Membership.MinRequiredPasswordLength inside your Razor view to pull in the value.

Resources