Does asp.net mvc client side validation using jQuery only work with views
which use HTML Helpers to generate HTML controls? Does it work with standard HTML Controls?
It is possible to use validation without turning to HtmlHelpers. See this article for details about how MVC works in the background with unobtrusive validation.
http://www.blinkingcaret.com/2016/03/23/manually-use-mvc-client-side-validation/
Though I think unless you have a very specific requirement, rather stick with Helpers, it will make your life easier.
1)Add Validation Property in model
2)In view add html control for show the validation
1)For Model
[Required(ErrorMessage = "Name is Required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is Required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
2)In View
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "error" })
3)Most Important (Add the following link in the View Page)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-
validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-
unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
Related
Is it possible to use validation messages in FluentBootstrap on form element level?
When I use:
#using (var form = Html.Bootstrap().Form().Begin())
{
#form.InputFor(m => m.Name)
#form.Submit()
}
There is no validation, except validation error class on input tag. I want to show validation message for Name property and has-error class on form-group container.
Just add #form.ValidationSummary() where you want the general validation summary to appear. There is an example of this as well as some other examples here: https://github.com/daveaglick/FluentBootstrap/blob/develop/FluentBootstrap.Tests.Web/Views/MvcTests/MvcForms.cshtml
If there is no particular reason to use InpuFor you can do the following.
#form.EditorFor(m => m.Name, addValidationMessage: true)
This will show what error message you put on your Name property's attribute.
Such as
[StringLength(50, ErrorMessage="Cannot be longer than 50 character.")]
public string Name { get; set; }
I personally use the base validation helper
#form.InputFor(m => m.Password, FormInputType.Password)
#Html.ValidationMessageFor(m => m.Password)
I can set the type of the input unlike the case when I use EditorFor
Okay I have searched it long enough to not find this anywhere on the net. So here is my question, in asp.net MVC (5.1) razor the default helper we can use DisplayNameFor to get the Name value from Display attribute is there anything similar for retrieving Description?
[Display(Name = "First Name", Description="What is your first name")]
public string FirstName { get; set; }
E.g.
#Html.DisplayNameFor(model=>model.FirstName)
Instead use LabelFor and try below code.
#Html.LabelFor(m => m.FirstName,
new{title=ModelMetadata.FromLambdaExpression<Models.Profile, string>
(m => m.FirstName, ViewData).Description})
I'm working on a webapp using ASP MVC. I'm building a page to edit a user's data (model USER, view ModifyUser).
I have a model with validations in this manner:
[MetadataType(typeof(USERS_Metadata))]
public partial class USER
{
public class USERS_Metadata
{
[Required(ErrorMessage = "FALTA NOMBRE")]
[StringLength(30, ErrorMessage = "Nombre entre 3 y 30 caracteres", MinimumLength = 3)]
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Error en el formato del nombre.")]
public string NAME { get; set; }
I then use a view that automagically validates user inputs:
<div class="editor-label">
<%: Html.LabelFor(model => model.SURNAME) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.SURNAME) %>
<%: Html.ValidationMessageFor(model => model.SURNAME) %>
</div>
The problem is my view is also gonna need to access some other entities with their own models, like USERCATEGORY, which makes using an strongly typed view a bit more uncomfortable.
Aditionally, and may be even more important, I don't want my view to have to deal with, and even knowing about, properties such as the user's session ID, which currently I handle like this (and i hate it):
<%: Html.HiddenFor(model => model.SESSIONID) %>
Unless I'm utterly mistaken, the most sane option is to build a custom ViewModel. I decided to build my ModifyUserViewModel to match those fields in USER I'm gonna need in my view, and add a few fields from the other models... But I have no idea of how to propagate the metadata in USER, that I use for field validation, to the new ViewModel. This metadata is automatically built from the database, and copypasting it would make me feel dead inside, even if it works.
What is the canonical, most maintenable, easiest way to validate from the View like I am currently doing, but with a ViewModel?
Try to build your view model as an aggregate of several domain models:
public class MyViewModel {
public USER User { get; set; }
public USERCATETORY Category { get; set; }
}
See a great article here.
I have a funny problem and I did not find the cause.
In asp.net MVC application I have a form that saves some simple information. All fields can be stored neatly except one. This field (string) returns validation error "The Int32 field must be a number" but only if the sentences in the text contains a single digit number. For example, if the sentence is as follows:
"Some simple sentence that contains the number 3" I'll get a validation error - "The Int32 field must be a number", if that same sentence transformed into:
"Some simple sentence that contains the number 30" or "Some simple sentence that contains a 30%" - no errors
Field property from a model:
[Display(Name = "Some name")]
[StringLength(500, ErrorMessage = "You can enter up to 500 characters.")]
public string Akcija { get; set; }
Next to that field I have one (string) field with the same property characteristics, and it is working properly.
Clip from view:
<div>
#Html.TextAreaFor(m => m.Akcija, new { style = "width:500px; height:100px;" })
#Html.ValidationMessageFor(m => m.Akcija)
</div>
It can not be simpler than that, but the problem is around here.
Do you have any suggestions?
Edit:
If I keep trying to save the changes it will be saved to the database regardless of the validation error. It seems to me that this is a JavaScript validation error or a bug
Edit 2 - Generated HTML:
<textarea cols="20" data-val="true" data-val-number="The field Int32 must be a number." data-val-required="The Int32 field is required." id="Akcija" name="Akcija" rows="2" style="width:500px; height:100px;">
Web aplikacije i siteovi 3 sa 30% sniženja
I do not know where it comes from - this attribute "data-val-number =" The field Int32 must be a number. '" And " data-val-required = "The Int32 field is required.'"
I'm not in the code imposed these rules
Try tagging the property with [DataType(DataType.MultilineText)]. Maybe that will make it explicit to the TextAreaFor helper.
If anyone ever run into this problem, the workaround is to use Html.EditorFor how it follows:
First: Add validation attribute [DataType (DataType.MultilineText)] to model property
so that model property looks like this:
[Display(Name = "Some name")]
[StringLength(500, ErrorMessage = "You can enter up to 500 characters.")]
[DataType(DataType.MultilineText)]
public string Akcija { get; set; }
Secondly: Make Template for Html.EditorFor.
Template create in a folder Views/Shared/EditorTemplates - if there is no folder EditorTemplates, make it.
In the folder EditorTemplates create a partial view named with the name of the model property.
In my case it is: akcija.cshtml
In this view should be forwarded the value of the model property and you must include the HTML that defines the field of view so that the template, in my case, look like this:
#model System.String
#if(!string.IsNullOrEmpty(Model))
{
<textarea name="Akcija" style="width:500px;height:100px;">#Model.ToString() </textarea>
}
else
{
<textarea name="Akcija" style="width:500px;height:100px;">#Model</textarea>
}
Third In your View change Html.TextAreaFor in Html.EditorFor and put a reference to your template. Html.EditorFor, in my case, now looks like this:
<div>
#Html.EditorFor(m => m.Akcija, "akcija")
#Html.ValidationMessageFor(m => m.Akcija)
</div>
And that's it, problem solved.
Note: When naming template and objects within the template and the template it self, note the naming convention. Note that my template is named with small letter and in html template there is no id attribute for html object.
I hope that this will help someone
Use a nullable int/Int32.
public int? mobilequantity { get; set; }
or
public Int32? mobilequantity {get; set;}
that works on my form
I'm using this code on an email field:
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[DataType(DataType.EmailAddress)] does not work (validation does not occur no at a server not on the client side).
I am not sure if I should implement myself a Custom Attribute or I can use one included with MVC 3.
Could you please suggest me a solution for creating a custom attribute in case I need to.
I read also about some additional extensions, example
http://nuget.org/packages/DataAnnotationsExtensions.MVC3
Would you suggest it to me?
You could use the usual DataAnnotations library by just using [EmailAddress]
using System.ComponentModel.DataAnnotations;
[Required]
[EmailAddress]
public String Email { get; set; }
Also just for reference, here's the regular expression version of this validation:
[RegularExpression(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
public String Email {get; set;}
Best of luck!
At the moment I have solved my problem using
DataAnnotationsExtensions
it just works, you add their library with NuGet
using DataAnnotationsExtensions;
[Required]
[DataType(DataType.EmailAddress)]
[Email]
public string Email { get; set; }
It looks like all the answers focus on the Data Model while this issue can be affected by the View itself.
The following on MVC .NET 4.5 is working alright:
Data model:
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email")]
public string Email { get; set; }
Razor View:
#Html.LabelFor(model => model.Email)
#Html.EditorFor(model => model.Email)
Note: do not need to add [EmailAddress] attribute. If you use [DataType(DataType.EmailAddress)] along with #Html.EditorFor() in your View, you should be fine.
As highlighted with rich.okelly, at the end you want your input rendered as <input type="email" />.
May be this will be helpful for someone. Following works for me
[Required(ErrorMessage = "*")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
But does not work following
[Required(ErrorMessage = "*")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
I am using MVC 5 & .NET 4.5
As Felix mentioned, the problem is on the View level, you need to use EditorFor() in your View instead of TextBoxFor(), the EditorFor() will render:
<input type="email" />
which will trigger the validation, while TextBoxFor() will render:
<input type="text" />
So in order to validate your entered email address, you need (in combination with EditorFor()) to use only:
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
This way, your entered value for email will be always validated, but if you don't enter a value for email, nothing will happen (unless you specified the [Required] attribute), the form will be submitted with an empty email address.
[DataType(DataType.EmailAddress)] can't recognize # and [EmailAddress] can't recognize .com , so use RegularExpression :
[RegularExpression(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]