I have got a model as below -
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Password and Confirm Password have to be the same")]
public string ConfirmPassword { get; set; }
In my HTML, I am adding the code as
<label>Password</label>
<span class="req">*</span>
#Html.PasswordFor(x => x.Password, new { #class = "form-control form-control2", #required = "required" })
<p class="signuppace"></p>
<label>Confirm Password</label>
<span class="req">*</span>
#Html.PasswordFor(x => x.ConfirmPassword, new { #class = "form-control form-control2", #required = "required" })
The message for the required field gets displayed but here the ErrorMessage "Password and Confirm Password have to be the same" doesn't get displayed. I have already referred this 1,2 SO links. What am I doing wrong? Any help would be appreciated.
The don't think that the helper adds markup to display a validation error automatically, other than for client side validation using unobtrusive client validation which executes using JavaScript (Not server side).
You want to use #Html.ValidationMessageFor(x => x.ConfirmPassword) to show the error message or simply check for the error using the ModelState.
#if (ModelState.Errors["ConfirmPassword"] != null && !string.IsNullOrWhiteSpace(ModelState.Errors["ConfirmPassword"][0]))
{
// Display the first error message for this field
ModelState.Errors["ConfirmPassword"][0]
}
You don't show all relevant cshtml, but you need to display the validation message.
Either use #Html.ValidationSummary(excludePropertyErrors: false) to display all validation errors in one place, or put #Html.ValidationMessageFor(x => x.Password) near your input field.
Related
I have a validation message for where I need to change the error message text at run time (when they click the submit button).
Based on what the id is passed in, the user has to send XML or a Query.
If they should send in a query, I want it to say: "The Query is required."
If they should send in xml, I want it to say: "The XML is required."
I've tried to clear the ModelState.Clear();
I've tried to NOT set the second parameter in ValidationMessageFor()... (usually it is "", but when I try to set it within there, then it automatically shows on the page when the page loads)
#Html.ValidationMessage("RawXmlOrQueryText", string.Format("The {0} field is required.", Model.Label), new { #class = "text-danger" })
if I do something like this, then it never shows period:
#Html.ValidationMessageFor(m => m.RawXmlOrQueryText, string.Format("The {0} field is required.", Model.Label), new { #class = "text-danger", style = "display:" + "none" + ";" })
Is there a better way to do this?
I want to be able to set the error message at run time and it to now show on the page until the user clicks the button.
Are you ok with using AddModelError()?
Assuming you are using this model:
public class IndexModel
{
public string QueryText { get; set; }
}
In your post method, add the following code:
var isXML = true; //oversimplification of your validation code
var someErrorMsg = isXML ? "The XML is required." : "The Query is required.";
ModelState.AddModelError(nameof(model.QueryText), someErrorMsg);
return View(model);
I am currently at an internship and am completely new to Razor and C# MVC. I am currently building a simple Razor form, but my validation is giving me grief for a check box.
Here is my model code:
[DisplayName("Sign me up for spam* ")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You must sign up for spam.")]
public bool Check { get; set; }
Here is my Razor markup:
#Html.LabelFor(model => model.Check, new { #class = "" })
#Html.CheckBoxFor(model => model.Check, new { #class = "example1"})
Here is the generated HTML:
<input class="example1" data-val="true" data-val-range="You must sign up for spam." data-val-range-max="True" data-val-range-min="True" data-val-required="The Sign me up for spam* field is required." id="Check" name="Check" type="checkbox" value="true">
<input name="Check" type="hidden" value="false">
I know that Razor will generate both inputs automatically. My problem is that the validation is simply not working on the check box. The model state is always invalid because of it, and on the client side the error message appears when the box is checked and disappears when the box is unchecked. I have been googling for answers, but have come up short and my mentor doesn't know what is going screwy either.
It looks like a client side reversed issue. Add this jquery in your page and I think it will be fixed:
<script>
// extend range validator method to treat checkboxes differently
var defaultRangeValidator = $.validator.methods.range;
$.validator.methods.range = function(value, element, param) {
if(element.type === 'checkbox') {
// if it's a checkbox return true if it is checked
return element.checked;
} else {
// otherwise run the default validation function
return defaultRangeValidator.call(this, value, element, param);
}
}
</script>
I'm using C# with MVC(Razor View Engine)
I'm doing validation using Annotation Like this:-
Model :-
[Required]
public int VendorId { get; set; }
Razor view Engine :-
<div class="col-md-3">
<label>#Html.LabelFor(r => Model.VendorId)</label>
#Html.DropDownListFor(x => x.VendorId, new SelectList(suppliers, "Value""Text"),"-Select-", htmlAttributes: new { #class = "select-full" })
#Html.ValidationMessageFor(x => x.VendorId, null, new { style = "color: red" })
</div>
and it was showing error message
The Vendor field is required.
if I'm not selecting vendor.
Now I want to highlight (Border Color in Red) of this Dropdown Field
instead showing this message if validation failed (DataAnnotation) instead showing a message on both client & server side
You can check validate form, if form is invalid, just add:
$('#VendorId').attr('style', "border-radius: 5px; border:#FF0000 1px solid;");
I need a help.
I have a User registration form and I have to map "Customer" with user.
Now I want to validate user "customer" which is came from another source and I put the "customer" in Select list "customer" are more then 2000 that's why I use JQuery Chosen plugin to search in select list
but "customer" Field depend on "roles" that's why on page load "customer" field is hidden by default when I change the role "customer" field(chosen select list) display and when i am Selecting customer its not firing remote validation.
I tried to make it visible on "inspect element" and I change the display:none to display:bock and try to change value from chosen its not working when i change the orignal select list value from clicking on select list then its working fine i mean its firing my remote validator method here is full code example what i am doing.
please help i want to validate on when chosen select list value change.
This is RegisterViewModel
public class RegisterViewModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
//for edit view model additionalFields which will only require for edit mode
//[System.Web.Mvc.Remote("DoesCustomerCodeExist", "Account", AdditionalFields = "OldCustomerCode")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Customer Code is required.")]
[Display(Name = "Customer Code", Description = "A customer code come from our oracle system.")]
[System.Web.Mvc.Remote("DoesCustomerCodeExist", "Account")]
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid Customer Code in number only.")]
public string CustomerCode { get; set; }
}
Here is my view cshtml in this file also have js code to display customers chosen Select list when role changed.
//select Role
<div class="form-group">
#Html.LabelFor(m => m.Role, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.Role, ViewBag.Roles as SelectList,"", new { #class = "form-control chosen-select", data_placeholder = "Select a Role" })
#Html.ValidationMessageFor(m => m.Role, "", new { #class = "text-danger" })
</div>
</div>
//Customer Code
<div class="form-group condition-div user hidden ">
//this hidden field is only for edit mode
//#Html.Hidden("OldCustomerCode", Model.CustomerCode)
#Html.LabelFor(m => m.CustomerCode, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.CustomerCode, (SelectList)ViewBag.Customers, "", new { #class = "form-control chosen-customers", data_placeholder = "Select Customer" })
#Html.ValidationMessageFor(m => m.CustomerCode, "", new { #class = "text-danger" })
</div>
</div>
#section Styles{
#Styles.Render("~/Content/chosen")
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/chosen")
<script type="text/javascript">
$('input[type=text]').tooltip(
{
placement: "right",
trigger: "focus"
}
);
$(".chosen-select").chosen({ allow_single_deselect: true});
$('#Role').change(function () {
if (this.value == "") {
$('.condition-div').addClass('hidden'); // hide all the conidional divs
} else if (this.value == "NBP User" || this.value == "NBP Head" ) {
$('.condition-div.admin').addClass('hidden'); /// hide admin conditional divs
$('.condition-div.user').removeClass('hidden'); // show user role conditioanl div
//configure selectlist to Chosen select and if i remove this line and show orignal select list its working fine mean remote validating on change but if i use this is not working on change.
$(".chosen-customers").chosen({ allow_single_deselect: true, search_contains: true });
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-customers)" });
} else if (this.value == "ICIL User" || this.value == "ICIL Head" || this.value == "FIO User" ) {
$('.condition-div.user').addClass('hidden'); /// hide user role conditional divs
$('.condition-div.admin').removeClass('hidden'); // show admin role conditional divs
$(".chosen-branch").chosen({ allow_single_deselect: true });
$.validator.setDefaults();
}
});
</script>
}
Controller Action to validate Customer Code
public ActionResult DoesCustomerCodeExist(string CustomerCode, string OldCustomerCode)
{
//the oldCustomerCode will come null in this case cause its register view and in edit view OldCustomerCode will be use
if (CustomerCode == OldCustomerCode)
return Json(true, JsonRequestBehavior.AllowGet);
if (DbContext.Users.Any(x => x.CustomerCode == CustomerCode))
return Json("Customer code already exists in application. Please verify user details.", JsonRequestBehavior.AllowGet);
if (DbOracle.IsCustomerCodeExist(CustomerCode))
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json("The customer code does not exist in database.", JsonRequestBehavior.AllowGet);
}
All code working fine if i did not use jquery chosen plugin.
In short issue is when I use chosen plugin for select list remote validation is stop validating values.
I can share images if u guys need now I have a limited account so i cant upload snaps shots....
Please help me.
you should have to put some JQuery on client side to track the "CustomerCode" field when change of customer field jsut call "focusout()" event of "CustomerCode" e.g:
$('#CustomerCode').change(function () {
$(this).focusout();
});
I have simple 1 page application to send email out to users. I have 3 fields for name, email and phone number. The code seems to work with input button, with validations firing and throwing proper error message. But I am more inclined towards using anchor tag (ActionLink) for my UI. The data still posts when I click on anchor tag (using jQuery) but the validations don't fire. Is there anything that I am missing or there's a better way of doing it?
I have used this post as reference.
Model
public class Contact
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Phone is required")]
public string PhoneNumber { get; set; }
}
View
<div>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control", placeholder="Name" })
#Html.ValidationMessageFor(model=>model.Name)
</div>
<div>
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", placeholder="Email" })
#Html.ValidationMessageFor(model=>model.Email)
</div>
<div>
#Html.TextBoxFor(model => model.PhoneNumber, new { #class = "form-control", placeholder="Phone" })
#Html.ValidationMessageFor(model=>model.PhoneNumber)
</div>
<div>
<input type="submit" value="Give me Free Advice" />
<div class="btn">
#Html.ActionLink("I want free advice", "designerhome")
</div>
</div>
<script>
$(function () {
$('.btn').click(function (e) {
$.post("/campaign/designerhome", { Name: $("#Name").val(), Email: $("#Email").val(), PhoneNumber: $("#Phone").val() }, function (result) {
//do whatever with the response
if (result.status == true) {
alert('Email submitted successfully');
}
});//end of post
});//end of click
});
</script>
Controller
[HttpPost]
public ActionResult designerhome(Contact contact)
{
if (ModelState.IsValid)
{
}
return View("Advert1");
}
We have some reasons why validation not working
1. Check appsettings in web config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Both Should be true if you want to run client side validation.
2. Seems in your code you are not using Form tag as it is posted in the question
Form tag is must for validation
3. Jquery is not properly refrenced on layout page
please check following jquery refrence on your layout page
jquery.unobtrusive*.js
jquery.validate*.js
Hope it will help you.
I would force the validation in your click handler, as jQuery seems to do that only for the automatic submit of the form (and not for the manual post() you are doing):
$('.btn').click(function (e) {
if ($('#YourFormIdHere').valid()) { // Will force validation
$.post(...);
}
});
As your making an Ajax request to the Action, your validations will not be reflected as the view is not rendered again. To stay on the same track you can return the JSON like
return Json(new {Valid = validState,
Errors = Get Errors FromModel State,
});
and then repopulate using the JavaScript.
Another Way could be around making custom Helpers which will |make a POST request to the desired Action.Code Reference for the same is here.
And at last what you can do is create a HTML button and make a POST request.
Simply style your input button to look like a link with the following CSS:
input[type=submit] {
background:none!important;
border:none;
padding:0!important;
color:#069;
text-decoration:underline;
cursor:pointer;
}
<input type="submit" value="Give me Free Advice" />
This will allow all the built in validation to work as is, with no difference to the user other than the appearance.
If your requirement is to use ajax to post you must manually call the validate method within the JavaScript with jquery unobtrusive.
This can be done with the following:
// replace the `formId` with the one defined in your view
var $form = $('#formId');
$.validator.unobtrusive.parse($form);
$form.validate();
if ($form.valid()) {
// Do post
}
In order to manually pull out the error messages you can use this:
$.each($form.validate().errorList, function (key, value) {
$errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
$errorSpan.html("<span style='color:red'>" + value.message + "</span>");
$errorSpan.show();
});
Which replaces the ValidationMessageFor markup with the failure messages.