MVC 3 show required , regular expression validation on different location - c#

I have made both Required and Regular Expression validation working.
the only problem is i want to show them both on different location within the page.
just like the required validation message will be shown before the textbox. the regular expression validation message will be shown after the textbox. How can i do it?
Here is my model code
[Required(ErrorMessage = "*")]
[RegularExpression(#"^[\w-]+(?:\.[\w-]+)*#(?:[\w-]+\.)+[a-zA-Z]{2,7}$", ErrorMessage = "Invalid Email")]
public string Email { get; set; }
Here is my View code
#Html.ValidationMessageFor(p => p.Email)
#Html.TextBoxFor(p => p.Email)
#Html.LabelFor(p => p.Email, "Email")
On the above code, both error messages will show before the textbox, i want to make something like this
#Html.ValidationMessageFor(p => p.Email) - required validation message which is "*"
#Html.TextBoxFor(p => p.Email)
#Html.LabelFor(p => p.Email, "Email")
#Html.ValidationMessageFor(p => p.Email) - regular expression validation message which is "Invalid Email"

There is nothing out of the box that would give you fine grain control over individual validation errors for a single control. You would need to manually parse the individual errors from the ModelState - see this example.

Related

I want to let my text box allow only text

I'm working on project using MVC3 + Razor.I want to let my text box allow only text. I tried to apply data annotation in my data model (First Code):
[DataType(DataType.Text ,ErrorMessage ="Error")]
but, it's not working.Could anyone help me ?
You need a regular expression as below:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Please input letters only")]
You could annotate your model like this:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string TextBoxData {get; set;}
Then in your view you would use the helper
#Html.EditorFor(model => model.TextBoxData)
#Html.ValidationMessageFor(model => model.TextBoxData )

Razor #Html.ValidationMessageFor() not displaying "validation error message"

#Html.RequiredLabelFor(x => x.FirstName)
#Html.TextBoxFor(model => model.FirstName, new { Name = "1.first_name", tabindex = "1" })
#Html.ValidationMessageFor(model => model.FirstName)
Is there a reason why when passing second parameter to #Html.TextBoxFor the field is being validated but "validation message" does not appear?
#Html.RequiredLabelFor(x => x.FirstName)
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
When using an overload that accepts only one argument (lambda expression) "validation message" is being displayed correctly.
In my understanding the actual property is not being recognized?
Backing property:
[StringLength(100, ErrorMessage = "Max length 100 characters")]
[Required(ErrorMessage = "This field is required")]
[Display(Name = "First name")]
public string FirstName { get; set; }
The unobtrusive validation library identifies 'things to display validation for' using the name attribute. It's not that specifying extra properties stops it from working, but you have changed the name property and not reflected the new name in your validation helper.
You can either stop changing the name attribute in your textbox helper (necessary if you use the default model binder to return your view), or you can use
#Html.ValidationMessage("1.first_name")
The above method is not a good idea unless you're using JS/JQuery to validate and submit your form data (via AJAX), for the reasons given by Stephen in comment to this answer.
You have changed the name attribute, so not only will it not post back and bind to your model, jquery.validate.unobtrusive can now no longer match up the controls since the input has a different name than the associated validation message
<input name="1.first_name" ... />
<span .. data-valmsg-for="FirstName" ..></span> // There is no control named FirstName

How do I force a validation summary to appear with FluentValidation?

I've got FluentValidation set up in my ASP.Net MVC 3 project. I have a form which has two inputs. Either can be blank, but not both.
Here's what I have:
RuleFor(x => x.username)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.email) == true)
.WithMessage("Please enter either a username or email address")
This correctly puts the error directly above my username field. However, when both fields are left blank I'd prefer the Validation Summary to show the message
Is there a way to do this? I've been thinking I could create an unused field in the model and put the error on that (if the other two are blank),
RuleFor(x => x.unused_field)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.email) == true && string.IsNullOrEmpty(x.username) == true)
.WithMessage("Please enter either a username or email address")
but this feels like an awkward way to do it. Is there a way I can just add a message to the validation summary?
The only reference I could find was this.
Now if your model is that simple and this rule is the only one then this rule should be enough:
RuleFor(x => x)
.Must(x => !string.IsNullOrWhiteSpace(x.Email) || !string.IsNullOrWhiteSpace(x.UserName))
.WithName(".") // This adds error message to MVC validation summary
.WithMessage("Please enter either a username or email address");
Just add #Html.ValidationSummary() to your view and you're good to go.
But if you're going to put more rules on your model then to my knowledge there is only one 'hacky' way I could think of:
in your controller action add this:
if (!ModelState.IsValid)
{
if (ModelState["."].Errors.Any())
{
ModelState.AddModelError(string.Empty, ModelState["."].Errors.First().ErrorMessage);
}
// ...
}
This will add first error message from "." property to model property (adapt it to your needs). Also you will have to do a #Html.ValidationSummary(true) to show only model level errors in validation summary.
Third option: add rule(s) to unused_property and use #Html.ValidationSummaryFor(x => x.unused_property) as a validation summary
Your issue can be solved with FluentValidation AbstractValidator.Custom:
Custom(m => String.IsNullOrEmpty(m.Username) && String.IsNullOrEmpty(m.Email)
? new ValidationFailure("", "Enter either a username or email address.")
: null);
Empty string in ValidationFailure constructor assures validation message is not bound to any input field so it appears in validation summary like
ModelState.AddModelError("", "Enter either a username or email address.")
would.

Disabled DateTime field is marked as required in MVC4 page

One of my models contains a property which looks like this
private Nullable<DateTime> myDate;
[Display(Name = "My Date")]
[Editable(false)]
// [DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public DateTime MyDate
{
get { return this.myDate?? new DateTime(1, 1, 1); }
set { this.myDate = value; }
}
// [DataType(DataType.Date)] is commented out because it's a leftover from some experiments I made.
In my "edit" view I render the property like this
// input.noborder { border: 0 none; }
#Html.EditorFor(model => model.MyDate, new { #readonly = true, #class = "noborder" })
#Html.ValidationMessageFor(model => model.InvoiceDate)
I did not create an EditorTemplate for DateTime type. Finally, in the scripts of the same view, I attach jQuery Datepicker
var $dpMyDate = $('[name=MyDate]');
$dpMyDate.datepicker();
I basically want to render a read-only datepicker (next step would be to implement more scripts which would enable it if some conditions are met).
Everything seems to work but upon clicking the "save" button, validation tells me that the field is required, but I expected it not to be, since I didn't put the [Required] attribute in the class. Also (but this might just be me assuming too much) it feels weird that a readonly input field would be required (how is one supposed to fill it?)
I don't see anything wrong with the code, am I missing something ?
From reading the comments it looks like you failed at the javascript validation that ASP.NET MVC adds. The issue is that, while your private field is nullable, the property is non-nullable (DateTime is a struct). ASP.NET MVC binds to the property and concludes that it is "Required" even though it's not marked as [Required].
As a result, ASP.NET MVC will generate javascript as if it were marked as a [Required] property. In particular, you used an EditorFor() and so the javascript ASP.NET MVC injects will treat it as required. Since it's a readonly form element I believe the javascript will complain.
The way to get around this is to use a DisplayFor() which doesn't have that javascript attached.
Note that if you have a nullable property that is [Required] but you don't want it to be editable, you'll actually need to do something extra in addition to using DisplayFor()--you'll need to submit something in the HTTP request that ASP.NET MVC knows how to model bind. The most popular option is an <input> element with type=hidden. Because the user has absolute control over the HTTP request he sends to the server, you would probably want to ignore the submitted value to prevent "overposting".
Try this,
Change this
#Html.EditorFor(model => model.MyDate, new { #readonly = true, #class = "noborder" })
to
#Html.TextBoxFor(model => model.MyDate, new { #readonly = true, #class = "noborder" })
And remove #Html.ValidationMessageFor(model => model.InvoiceDate) it's no need.
I think its because your date not Nullable.
Try to define it like
public DateTime? MyDate

Custom validating a Model object in MVC

I I need to validate some thing in mvc in my controller I have to
#Html.ValidationMessageFor(model => model.somestring)// in the view
if (model.string = some condition)
ModelState.AddModelError("somestring", "String cannot be empty");// in the controller
but if in my view I have a custom object like
#Html.ValidationMessageFor(model => model.someobject.somestring)// in the view
how do I validate it? Is the following syntax correct?
if (model.someobject.somestring = some condition)
ModelState.AddModelError("somestring", "String cannot be empty");// in the controller
You need to make sure the full path to your property is used when specifying your key:
ModelState.AddModelError("someobject.somestring", "String cannot be empty);

Categories

Resources