MVC3 error message declared in my model isn't taking effect - asp.net-mvc-3

[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!")]

Related

Phone Data Annotation .Net Core 1.1 not validating

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.

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 validate textbox in MVC3 that must contain string started with characters "PR"

i am very much new to MVC3 and working with MVC3 razor application. I need to validate a textbox on View in such a way that, the textbox will accept only those strings which are starting with characters "PR" and 4th character of that string must be "2". It would be great if anybody helps me. Thanks in advance
Well you need regex. I'm not exactly sure what the regex would be and what your string contains. But if you need to have 2 matches in there, you could split it and use 2 textboxes and join the values on post.
ViewModel:
public class MyViewModel
{
[RegularExpression("^PR[A-Za-z0-9]", ErrorMessage= "Invalid Text1")]
public string MyText1 { get; set; }
[RegularExpression("^2[A-Za-z0-9]", ErrorMessage= "Invalid Text2")]
public string MyText2 { get; set; }
}
Warning, this regex may be faulty. I invite others to edit/post comments and i can update it with correct regex
View:
#model MyProject.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.MyText1)
#Html.TextBoxFor(m => m.MyText2)
<button type="submit">Submit</button>
}
Hope this helps
Model
public class RegisterModel
{
public int ID { get; set; }
[RegularExpression(#"^PR[a-zA-Z0-9]2([a-zA-Z0-9]*)$", ErrorMessage = "Please enter valid Name.")]
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}
View
#using (Html.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post, new { id = "FrmIndex" }))
{
<div>
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
}

MVC3 Navigation Property Attributes and Client Side Validation

I am making my first tentative steps into MVC3 and have come across an issue with the translation of navigation properties within a model to a view. It seems that in the view navigational properties do not allow client side validation nor is the "Display" label attribute picked up.
I have the following simple model:
public class Entity
{
[Key,
ScaffoldColumn(false)]
public int Entity_Id { get; set; }
[Display(Name = "Entity Name"),
Required(ErrorMessage = "Please enter the entity name."),
StringLength(150, ErrorMessage = "Please ensure that the entity name is under 150 characters.")]
public string Entity_Nm { get; set; }
[Display(Name = "Entity Type"),
Required(ErrorMessage="Please select the entity type"),
ForeignKey("EntityType")]
public int EntityType_Id { get; set; }
public virtual EntityType EntityType { get; set; }
}
Which references this model:
public class EntityType
{
[Key]
public int EntityType_Id { get; set; }
[Display(Name = "Entity Name"), Required(ErrorMessage="Please enter the entity type name.")]
public string EntityType_Nm { get; set; }
}
When I create a controller with read/write actions and views for this model I get the following create form:
<fieldset>
<legend>Entity</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Entity_Nm)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Entity_Nm)
#Html.ValidationMessageFor(model => model.Entity_Nm)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EntityType_Id, "EntityType")
</div>
<div class="editor-field">
#Html.DropDownList("EntityType_Id", String.Empty)
#Html.ValidationMessageFor(model => model.EntityType_Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
This is fine apart from the label for the Entity Type drop down, for some reason it is not picking up the "Display" attribute of the navigation property within the model (note the lack of a space). Also client side validation is not enabled for the dropdown list (server side validation works without issue) despite decorating the property with a "Required" attribute. Client side validation works on the other fields. Please note that all the required .js script files have been included and I have also added the relevant enable validation keys to the web.config.
Any ideas what I am missing here? Thanks one and all.
for DropDownList Display issue just try below
#Html.LabelFor(model => model.EntityType_Id)

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})

Resources