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/
Related
i have setup the route to be:
[Route("{id}/users/search/{search}")]
and the associated action is:
SomeAction(int id, string text)
The service has the following function.
for the resource with id={id} and the users of this resource get the users that match with the {search} term (username, email etc).
the {search} can have a value so the service returns only the matching entities or does not have a value (empty string or null) so the service returns everything.
For the part with a value it works fine.
For the second part i cannot find something to set the get request that matches the empty string.
i tried the following:
1/users/search/null {search} = "null"
1/users/search/ does not match route
1/users/search does not match route
has anyone a hint how this could be done?
Update: i have tried to replace the action:
SomeAction(int id, string text)
with:
SomeAction(Model model) where model is
public class ApplicationUserSearchModel
{
[Required]
public int Id { get; set; }
[Required(AllowEmptyStrings = true)]
public string MatchText { get; set; }
}
with no luck since i don't know what to send in order to match the url to this.
You should tag your search parameter with ? to mark it as optional in the route, and set it to null by default in your action.
[Route("{id}/users/search/{search?}")]
public HttpResponseMessage Search(int id, string search = null)
I originally thought the route/action parameter names were the issue, but I was incorrect. Here is the previous answer:
The parameter names in your route definition and your action don't match, which is causing your problem.
[Route("{id}/users/search/{search}")]
public HttpResponseMessage Search(int id, string text)
You should update the string parameter in your action from text to search, to match the parameter name in your Route attribute.
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
Imagine you have two fields in your Model:
public class MyModel
{
[Required(ErrorMessageResourceType = typeof(Resources.Resource), ErrorMessageResourceName = "DateRequired"]
public DateTime Date;
[DataType(DataType.Currency, ErrorMessageResourceType = typeof(Resources.Resource), ErrorMessageResourceName = "NumberError")]
public decimal Number;
}
My problem is this: If the user enters a non-valid Date (like 'aaa') or a non-valid Number (like 'bbb') then the standard jQuery validation messages kicks in like: 'The field Number must be a number' (and the same goes for Date).
How do I get a localized error message for my fields? I know I can convert my fields to strings and then manually convert these fields to my corresponding database fields, but I believe there must be an easier way.
You should load the correct "messages_##.js" file for your language. For instance, when I need brazilian portuguese validation, I use:
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/localization/messages_ptbr.js
Just replace "ptbr" at the end with your localization code. Of course, you can just get the code and use your own messages.
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