Phone Data Annotation .Net Core 1.1 not validating - validation

I think the [Phone] annotation should be applying a standard regex pattern to the UI input field but I am finding that I can enter anything words, all manner of special characters and no validation errors occur.
Below is the HTML and then Model entry
<div class="form-group">
<label class="col-sm-3 control-label">#Html.DisplayNameFor(m => m.Supplier.Phone)</label>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.Supplier.Phone, new { #class = "form-control", id = "Phone" })
<span asp-validation-for="Supplier.Phone" class="text-danger"></span>
</div>
</div>
[Required]
[Phone]
public string Phone { get; set; }
All other validations such as [EmailAddress], [Range] and [Required] are working just fine.
I did come across this stackoverflow article suggesting the HTML5 did not support phone, is that still correct?

Yes. You have to use regex for that.
e.g.
[RegularExpression("^[0-9]*$", ErrorMessage = "The Phone Number field must contain only numbers")]
or
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
The first one will allow only numeric values while second one will allow formats like 0123456789, 012-345-6789, (012)-345-6789 etc.

Related

Data annotation on int[]

In a ASP.NET MVC5, I'm using the chosen JS library for a multi-dropdown select. How Can I do to use Data Annotation to validate the field?
Actually I use [Required] on all fields, this multi-dropdown select too, but it isn't working.
Code:
[MinLength(1)]
public int[] fields{ get; set; }
Here is my Code in the cshtml:
#Html.ListBoxFor(x => x.fields, Model.fieldsSelect, new { data_placeholder = "pholder" })
#Html.ValidationMessageFor(model => model.fields, "", new { #class = "text-danger" })
Without the plugin I currently use (chosen) there is no validation , Here is the HTML rendered without chosen:
<div class="col-md-10">
<select data-placeholder="Enter multiple fields" data-val="true" data-val-minlength="The field fieldsmust be a string or array type with a minimum length of '1'." data-val-minlength-min="1" id="fields" multiple="multiple" name="fields">
<option value="944454">WARUYFJGHIE</option>
<option value="33033095">WEBJKHGJHGVHGAN</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="fields" data-valmsg-replace="true"></span>
</div>
Validation works for all my string but not this one: when I select nothing on the form, all [Required] for strings works: an error message is apparing and submit is not hitting the controller/server, but not the [MinLength(1)]... No error message and when I fill all except [MinLength(1)], the form is submitting and error occurs in the controller/server because of null.
Versions of JS validations:
jQuery Validation Plugin - v1.11.1 - 3/22/2013
jquery.validate.unobtrusive.min.js : no version (neither in the
jquery.validate.unobtrusive..js)
You can use the MinLengthAttribute
[MinLength(1)]
public int[] fields{ get; set; }
Edit
Based on additional comments, a jquery plugin is being used that hides the <select>. By default hidden fields are not validated. To include hidden fields, add the following
$.validator.setDefaults({
ignore: []
});

Custom error message with DataAnnotationsExtensions

I'm trying to get Scott Kirkland's DataAnnotationsExtensions to work with my MVC4 project. But I'm having problems with the client side validation of an email address. I've added a EmailAddress annotation with a error message, but when I enter an invalid email address I do not get the custom error message, but instead I get the generic email error message "Please enter a valid RecipientEmail address.".
My class looks like this:
public class NpRequest
{
[DisplayName("Telefonnummer som skal overdrages")]
[Required(ErrorMessage = "Angiv telefonnummeret som skal overdrages")]
public string PhoneNumer { get; set; }
[DisplayName("Recipient email address")]
[EmailAddress(ErrorMessage = "This is my custom error message")]
[Required(ErrorMessage = "The recipient email address is required")]
public string RecipientEmail { get; set; }
public RecipientTypeEnum RecipientType { get; set; }
}
And my view:
---SNIPPET BEGIN---
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumer)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNumer)
#Html.ValidationMessageFor(model => model.PhoneNumer)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RecipientEmail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RecipientEmail)
#Html.ValidationMessageFor(model => model.RecipientEmail)
</div>
<p>
<input type="submit" value="Create" />
</p>
---SNIPPET END---
EDIT:
When I inspect the HTML it looks like this:
<input class="text-box single-line input-validation-error" data-val="true" data-val-email="This is my custom error message" data-val-required="The recipient email address is required" id="RecipientEmail" name="RecipientEmail" type="email" value="">
It seems that my custom error message is put into the data-val-email attribute. I was under the impression that the DataAnnotationExtension automatically added my custom error message to the ModelState and thereby also adding it to the field-validation-error span, which is showing the MVC validation error.
Is this assumption wrong? Should I write my own javascript, which extracts the custom error message attribute and injects it into the field-validation-error span?
Can anyone see what I'm doing wrong?
I ended up using a mix of System.ComponentModel.DataAnnotations and DataAnnotationsExtensions. I found out out that most of the time data annotations will also make client side validation. The only time where is no client side validation, is when I check if the phone number is the correct length.
public class NpRequest
{
[DisplayName("Phone number")]
[MinLengthAttribute(8, ErrorMessage = "Phone number must be 8 digits")]
[MaxLengthAttribute(8, ErrorMessage = "Phone number must be 8 digits")]
[DigitsAttribute(ErrorMessage = "Phone number must be 8 digits")]
[Required(ErrorMessage = "Phone number is required")]
public string PhoneNumber { get; set; }
[DisplayName("Modtagers email adresse")]
[EmailAddressAttribute(ErrorMessage = "Invalid email")]
[Required(ErrorMessage = "Email is required")]
public string RecipientEmail { get; set; }
public RecipientTypeEnum RecipientType { get; set; }
}

How to create string template with validation message and watermark in MVC 3

I'd like to create template for string, that will include label, textbox with watermark and validation message for registration form.
In addition, I'd like to add notice (eg. star), that the field is required by getting it from model.
So far I have created file string.cshtml in ~/Views/Account/EditorTemplates containing this:
<span class="editor-label>#Html.Label(ViewData.ModelMetadata.Watermark)</span>
<span class="editor-field">#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = ViewData.ModelMetadata.Watermark })</span>
<span class="error_message">#Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)</span>
Model looks like this:
[Required]
[DataType(DataType.Text)]
[Display(Prompt = "First name")]
public string FirstName { get; set; }
And in view I call it as follows:
#Html.EditorFor(m => m.FirstName)
Does anyone have any idea, where do I go wrong?
Your editor template must be called Text.cshtml and not String.cshtml because you use the [DataType(DataType.Text)] attribute.
You could also specify a custom name for the editor template using the UIHint attribute:
[Required]
[DataType(DataType.Text)]
[Display(Prompt = "First name")]
[UIHint("Foo")]
public string FirstName { get; set; }
and now you could have ~/Views/Account/EditorTemplates/Foo.cshtml.
Andree,
Your problem for not showing the message is this line:
<span class="error_message">#Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)</span>
If you look at your rendered HTML source, you see something like the following:
<span class="field-validation-error" data-valmsg-for="<className>.FirstName" data-valmsg-replace="true"></span>
Notice, that it's including the class in the data attribute. However, ubobtrusive doesn't match this. What you need rendered is simply:
<span class="field-validation-error" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>
In order to accomplish this, change your code in your editor to:
#Html.ValidationMessageFor(v => v)
Likewise, to make you code easier to read, both of these also work for your other code...
#Html.LabelFor(v => v)
#Html.TextBoxFor(v => v, new { placeholder = ViewData.ModelMetadata.Watermark })

How are you meant to use Prompt, Description, Ordering when applying data-annotations in ASP.NET MVC 3

I have a view model with a property on it that looks like this:
[Display(Name = "Some Property", Description = "This is description", Prompt = "This is prompt")]
[Required(ErrorMessage = RequiredFieldMessage)]
public string SomeProperty { get; set; }
But this does not seem to render anything extra in the view. Do you need to do some additional work?
<div class="editor-label">
#Html.LabelFor(model => model.SomeProperty )
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.SomeProperty , 5, 80, null)
#Html.ValidationMessageFor(model => model.SomeProperty )
</div>
Not all of the built in EditorTemplates take advantage of all of the DataAnnotations, but they are there for when you write your own EditorTemplates you can leverage them.
Ordering doesn't really apply unless you are doing DisplayForModel or EditorForModel where its showing multiple editors for all the properties on the model, it can then order the Editor's appropriately.
If you wanted to take advantage of the Description and Prompt metadata you could write your own String EditorTemplate:
#model string
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new {
#title = ViewData.ModelMetadata.Description,
#placeholder = ViewData.ModelMetadata.Watermark})

MVC3 error message declared in my model isn't taking effect

[Required(ErrorMessage = "ONLY TYPE IN NUMBERS!")]
[Display(Name = "Telefono Fijo")]
public int Telephone { get; set; }
Basically, I'd like that when someone types in a letter, that text up there should display.
Here's my view:
<div>
#Html.LabelFor(model => model.RegisterModel.Telephone)
#Html.EditorFor(model => model.RegisterModel.Telephone)
#Html.ValidationMessageFor(model => model.RegisterModel.Telephone)
</div>
When I type in letters, I get:
"The field Telefono Fijo must be a number."
And when I don't type in ANYTHING, I get:
"ONLY TYPE IN NUMBERS!"
Any ideas? I only want the custom message to show.
You should use RegularExpressionAttribute:
[RegularExpression(#"^\d+$", ErrorMessage = "ONLY TYPE IN NUMBERS!")]

Resources