Email validation not working in MVC - asp.net-mvc

In my MVC application, email validation is working perfectly locally but when I m publishing and deploying to server It won't work. I have compared the html source of both local and deployed files and there is no difference. My Razor view mark up is
<li>
<p><strong>Email: </strong>#Model.CurrentEmailAddress <span class="deliverychange" onclick="showHidden('emailchange');">(Change email)</span></p>
<div id="emailchange" class="fullborder" style="display: none;">
<div class="orderrow newemailaddress">
#Html.LabelFor(m => m.UpdatedEmailAddress)
#Html.TextBoxFor(m => m.UpdatedEmailAddress, new { #onkeypress = "showEmailChangeConfirmation();" })
#Html.ValidationMessageFor(m => m.UpdatedEmailAddress)
</div>
<div id="updatedemailkeypress" style="display: none;">
<div class="orderrow checkboxrow emailchangeconfirm">
#Html.LabelFor(m => m.UpdateEmailAddress)
#Html.EnumRadioButtonFor(m => m.UpdateEmailAddress, false)
</div>
</div>
<div class="clear"> </div>
</div>
</li>
and my model is as
[DataType(DataType.EmailAddress)]
[RegularExpression(#"^([\w.-]+)#([\w-]+)((.(\w){2,3})+)$", ErrorMessage = "Email is not valid")]
[Display(Name = "Enter new email address: ")]
public string UpdatedEmailAddress { get; set; }
[Display(Name = "We will use ****")]
public YesNo UpdateEmailAddress { get; set; }

Use the EmailAddress-attribute instead
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.emailaddressattribute%28v=vs.110%29.aspx

Please recheck that form tag is there.
Form validation works actually by validating form valid method.
So, the form is required to be exist.
Hope this helps.

After spending a lot of time on this I found the publish wizard is not copying the jquery.validate-vsdoc.js to the scripts folder. I manually copied this to the server and all started working.

Try to use dataannotationsextensions library, you can download from nuget.
and just add Email attribute to your model like this
using DataAnnotationsExtensions;
[Required]
[DataType(DataType.EmailAddress)]
[Email]
public string UpdatedEmailAddress { get; set; }

Related

asp.net mvc client side validation using jQuery

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>

How to validate against a Model's metadata through a custom ViewModel?

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.

How to use a simple calender in MVC 4 Razor

I am very new on MVC. How can I use a calender? Here is my div
<div class="editor-field">
#Html.EditorFor(model => model.CommunicationTime)
#Html.ValidationMessageFor(model => model.CommunicationTime)
</div>
But it shows only a text box. What should I do?
try to add Data annotations DateType(DateType.Date) within your model
here is a sample :
[Display(Name = "Date of Birthday")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
this Should work in Chrome , Firefox , Safari or any browser Supports HTML5
that's because the produced html tags will contain type="Date" in date field

MVC CheckBoxFor causing unobtrusive validation to be bypassed

I have a form containing a number of controls - nothing fancy:
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<fieldset>
<legend>EmployeeViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Employee.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Employee.Title)
etc.....
UPDATE
My ViewModel:
public class EmployeeCreateViewModel
{
public EmployeeCreateModel Employee { get; set; }
..etc
My Employee model:
public class EmployeeCreateModel
{
[Required]
public string Title { get; set; }
[DisplayName("Job Title")]
[Required]
public string JobTitle { get; set; }
public bool Active { get; set; }
...etc
The Problem - I am using unobtrusive validation which works fine UNTIL I add a checkbox to the form. Regardless of the checkbox state, the form is submitted, bypassing client-side validation and errors are caught by the server-side validation. This is my checkbox:
<div class="editor-label">
#Html.LabelFor(model => model.Employee.Active)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.Employee.Active)
</div>
The checkbox model property is not a required field, so it doesn't need to be validated and I can see that it has a valid True/False value when it reaches the controller method.
Why is this happening, and how can I fix it?
First, open javascript console (e.g., chrome inspector panel) and see if you are getting Uncaught TypeError: Object [object Object] has no method 'live' error from jquery.unobtrusive-ajax.js.
If you are seeing this error, you are probably using jquery 1.9.x or higher. If you check "Preserve log upon navigation" (chrome), you can see an error saying "Uncaught SyntaxError: Unexpected token u".
To solve this problem, include jquery migrate 1.2.x after jquery 1.9.x.
<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
For details, see this post.

How add custom validation to my razor page?

I have razor page in my mvc 4 application .Now imagine i have a simple textbox in my page as follows :
#Html.TextBox("Email")
or
<input id="Email" name="Email" type="text" />
how can I do some client-side validation for this field you know something like asp.net web forms validation controls . I want to make it required and write a Regex for it .
I use to do this:
In the model Person.cs :
[StringLength(50, ErrorMessage = "El campo {0} no puede tener mas de 50 caracteres")]
[Required(ErrorMessage = "El nombre es obligatorio")]
public string Nombre { get; set; }
In the page Create.cshtml:
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Person.Nombre" class="control-label">Nombre / Name:</label>
<input asp-for="Person.Nombre" class="form-control" />
<span asp-validation-for="Person.Nombre" class="text-danger"></span>
</div>
You generally decorate your model properties with the RequiredAttribute and the RegexAttribute.
You may want to look at Data Annotations. They provide very simple and straightforward way for you to define your (not only) validation for every field in every view model.
Please take a look at the following link:
How to: Validate Model Data Using DataAnnotations Attributes
In your particular case, it will be
[Required]
[RegularExpression(#"<your RegEx>", ErrorMessage = "<your message, leave out for default>")]
public string fieldYouValidating { get; set; }
Other way for validation preferrable by many is Fluent Validation
RuleFor(x => x.fieldYouValidating)
.NotEmpty()
.WithMessage("This is the message.");
Hope this helps

Resources