My target is put an expression and validation message in this model, If it's wrong type the validation message from sql table will show on display but it has an error :
The resource type
'SupplierPortal.Data.Models.MappingTable.Tbl_LocaleStringResource'
does not have an accessible static property named
'_ComPro.Addtional.CompAddtional.LblNoOfEmp'.
How can I fix this?
Here is my code
Model
SupplierPortal.Data.Models.MappingTable.Tbl_LocaleStringResource = my data message name
_ComPro.Addtional.CompAddtional.LblNoOfEmp = my data message value
public partial class GeneralInfosModel
{
[RegularExpression("[0-9]+",ErrorMessageResourceType=typeof(SupplierPortal.Data.Models.MappingTable.Tbl_LocaleStringResource),ErrorMessageResourceName="_ComPro.Addtional.CompAddtional.LblNoOfEmp")]
public Nullable<int> NumberOfEmp { get; set; }
}
View
<div class="form-inline">
<div class="form-group margin none">
<div class="form_item">
#Html.TextBoxFor(m => m.NumberOfEmp, new { #class = "form-control", id = "NumberOfEmp", maxlength = "255", placeholder = "", #style = "width: 132px;" })
</div>
</div>
<div class="form-group margin-none">
#Html.ValidationMessageFor(a => a.NumberOfEmp, "", new { #class = "text-danger-bold" })
</div>
</div>
Related
In the ViewModel, I have Data Annotations for few fields.
public class EmployeeContactInfoVM
{
[Key]
public int slNo { get; set; }
[Required]
[Display(Name = "Employee GlobalView ID *")]
[StringLength(8,MinimumLength = 8,ErrorMessage ="GV ID should be 8 digits")]
[RegularExpression(#"^[0-9]+$", ErrorMessage = "Please use Numeric data")]
public string EmployeeID { get; set; }
[Required]
[Display(Name = "First Name *")]
[RegularExpression(#"^[a-zA-Z]+[ ]*[a-zA-Z]*$", ErrorMessage = "Please use letters")]
public string FirstName { get; set; }
}
My View code is given below
#model EmployeeContactInformation.ViewModel.EmployeeContactInfoVM
#using EmployeeContactInformation.Classes;
#{
ViewBag.Title = "Index";
}
#section Scripts
{
<script src="https://www.google.com/recaptcha/api.js?render=#ViewBag.SiteKey"></script>
<script>
function CreateToken() {
$.blockUI();
grecaptcha.execute('#ViewBag.SiteKey', { action: 'homepage' }).then(function (token) {
document.getElementById("tokenID").value = token;
document.EmpContactFrm.submit();
});
}
</script>
}
#using (Html.BeginForm("Index", "EmployeeContactInformation", FormMethod.Post, new { name ="EmpContactFrm", id = "EmpContactFrmID" }))
{
<div class="form-horizontal" role="form">
<hr />
#Html.ValidationSummary(true)
<input type="hidden" id="tokenID" name="token" />
<div class="form-group" style="margin-bottom:5px">
#Html.LabelFor(model => model.EmployeeID, new { #class = "col-md-2 editor-label" })
<div class="col-md-10 inputText">
#Html.TextBoxFor(model => model.EmployeeID, htmlAttributes: new { #title = "Employee
GlobalView ID should consist of 8 digits and in some countries it may start with a leading
zero" })
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "editor-label col-md-2" })
<div class="inputText col-md-10">
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SurName, new { #class = "editor-label col-md-2" })
<div class="col-md-10 inputText">
#Html.TextBoxFor(model => model.SurName)
#Html.ValidationMessageFor(model => model.SurName)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="button" value="Submit" class="btn btn-create btnSave" style="font-size:
large;font-weight: 600;padding: 10px;" />
</div>
</div>
}
The form gets submitted in CreateToken function ( document.EmpContactFrm.submit(); ).
I am assuming that all of the validations happen at client Side as I have included
in configuration file.
Some of the validation happen at Client side for e.g If I input 7 digit EmployeeID, I get an message saying "GV ID should be 8 digits".
When I submit the form without entering for mandatory fields, client Side validation doesn't work, the control comes to Action Method.
I have included Server Side Validation like if(ModelState.IsValid) in the code, this will now throw validation error when I miss Mandatory fields.
Do I need to include validation at both Server & Client End?
I was assuming that if we include jquery unobtrusive file & the above mentioned config settings, validations can be purely at client side.
Please let me know
Change this line from
#Html.ValidationSummary(true)
to
#Html.ValidationSummary()
Read this answer
I have few textbox that validates when its empty, but they dont work well. Below is my logic from the model to view, what could i be missing? Currently these textbox dont seem to work and no error when i inspect from the browser. The application is on asp.net mvc using bootstrap.
[DataType(DataType.EmailAddress)]
[Required(ErrorMessage = "This field is required")]
[RegularExpression(#"^\w + ([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")]
public string Email { get; set; }
// View
<div class="row">
<label for"Email">Email:</label>
<div class="input-group col-md-4 col-md-offset-2 col-sm-2 col-xs-2">
<div class="input-group pull-right">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", type = "text", id = "email", autofocus = "autofocus", placeholder = "example#example.com", required = "required" })
#Html.ValidationMessageFor(m => m.Email, " ", new { #class = "text-danger" })
<div class="input-group-append">
<div class="input-group-text">
</div>
</div>
</div>
</div>
</div>
NB: even if i use #html.EditorBoxFor(m=>m.Email, new {Form...}) still nothing and no error.
I've created new MemberType with some extra custom properties, marked as Mandatory.
In the registration form I want these properties to be set as required, so if you don't fill them, you won't be able to proceed with the registration of a new member.
In the Member section, the properties are correctly set as Mandatory.
Here's a screenshot: https://i.ibb.co/bR4sd2v/immagine.png
Here's my code of the registration form:
using (Html.BeginUmbracoForm<UmbRegisterController>("HandleRegisterMember"))
{
<div class="row justify-content-center no-gutters">
<div class="col-8 mx-auto pt-5">
#Html.ValidationSummary("registerModel", true)
#if (registerModel.MemberProperties != null)
{
<div class="form-row justify-content-center">
<div class="form-group col-md-6">
#Html.TextBoxFor(m => registerModel.MemberProperties[0].Value, new { #class = "form-control rounded-0", #placeholder = registerModel.MemberProperties[0].Name})
#Html.HiddenFor(m => registerModel.MemberProperties[0].Alias)
#Html.ValidationMessageFor(m => registerModel.MemberProperties[0].Alias)
</div>
<div class="form-group col-md-6">
#Html.TextBoxFor(m => registerModel.MemberProperties[1].Value, new { #class = "form-control rounded-0", #placeholder = registerModel.MemberProperties[1].Name})
#Html.HiddenFor(m => registerModel.MemberProperties[1].Alias)
#Html.ValidationMessageFor(m => registerModel.MemberProperties[1].Alias)
</div>
</div>
}
<div class="form-row justify-content-center pt-5">
<div class="form-group col-md-6">
#Html.TextBoxFor(m => registerModel.Email, new { #class = "form-control rounded-0", #placeholder = "Email"})
#Html.ValidationMessageFor(m => registerModel.Email)
</div>
<div class="form-group col-md-6">
#Html.PasswordFor(m => registerModel.Password, new { #class = "form-control rounded-0", #placeholder = "Password"})
#Html.ValidationMessageFor(m => registerModel.Password)
</div>
</div>
<div class="form-row justify-content-center pt-5">
<div class="form-group col-md-6">
<button class="btn btn-light text-uppercase w-100" type="submit">Registrati</button>
</div>
</div>
</div>
</div>
#Html.HiddenFor(m => registerModel.MemberTypeAlias)
#Html.HiddenFor(m => registerModel.RedirectUrl)
#Html.HiddenFor(m => registerModel.UsernameIsEmail)
}
I expect that when I click on the Sumbit button (in my case is "Registrati"), under the input fields will appear the validation message saying that those fields are required. And the registration could not proceed until I fill them.
Like it happens with the standard fields Email and Password. Here's a screenshot: https://i.ibb.co/z2cD3TC/immagine.png
How can I check if those fields are required, and show the error message?
Your fields may be required within Umbraco, but the code in your views doesn't know that. In order to achieve validation through the HTML Helpers you're using, you'll need to create a ViewModel like this:
public class MyViewModel
{
[Required(ErrorMessage = "Full name is required")]
public string FullName { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password, ErrorMessage = "Password is invalid")]
public string Password { get; set; }
}
Your HTML helpers should then understand which fields are required and which aren't, which means you can get both clientside validation as well as serverside validation :)
I'm trying to implement Remote Validation for a field in a view. Everything so far is working except the parameter in the validation controller method is null even though the field contains a value. What did I miss?
Validation Controller Method
public JsonResult IsVanityURL_Available(string VanityURL)
{
if (!_webSiteInfoRepository.GetVanityURL(VanityURL))
return Json(true, JsonRequestBehavior.AllowGet);
string suggestedUID = String.Format(CultureInfo.InvariantCulture,
"{0} is not available.", VanityURL);
for (int i = 1; i < 100; i++)
{
string altCandidate = VanityURL + i.ToString();
if (_webSiteInfoRepository.GetVanityURL(altCandidate)) continue;
suggestedUID = String.Format(CultureInfo.InvariantCulture,
"{0} is not available. Try {1}.", VanityURL, altCandidate);
break;
}
return Json(suggestedUID, JsonRequestBehavior.AllowGet);
}
Entity Property
[DisplayName("Vanity URL")]
[Remote("IsVanityURL_Available", "Validation")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed.")]
[Editable(true)]
public string VanityURL { get; set; }
View
<div class="row">
<div class="form-group col-md-12">
<div class="editor-label">
#Html.LabelFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL)
</div>
<div class="input-group margin-bottom-small">
<span class="input-group-addon"><i class="fa fa-external-link-square fa-fw"></i></span>
#Html.TextBoxFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL, new { #class = "form-control", #placeholder = "Enter Vanity URL" })
</div>
</div>
</div>
UPDATE
The answer in the duplicate post does fix the problem.
I found an alternate way to avoid changing the jquery.validate.js file. This involved setting the name of the TextBoxFor in the view like so...
#Html.TextBoxFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL, new { #class = "form-control", #placeholder = "Enter Vanity URL", #Name="VanityUrl })
I reverted my js file change, then added a combination of the view name attribute and the model remote AdditionalFields definition and it worked just fine.
This change caused some unforeseen problems as well. I finally did get a solution. I changed the GET to a POST and grabbed the values I needed from the FormsCollection. This link got me going in the right direction. This allowed me to completely bypass the Complex Data Object naming problem
change your entity
[DisplayName("Vanity URL")]
[Remote("IsVanityURL_Available", "Validation",AdditionalFields = "VanityURL")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed.")]
[Editable(true)]
public string VanityURL { get; set; }
and add this to your view
#{
var VanityURL=Model.SelectedContact.WebSiteInfoes[0].VanityURL
}
<div class="row">
<div class="form-group col-md-12">
<div class="editor-label">
#Html.LabelFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL)
</div>
<div class="input-group margin-bottom-small">
<span class="input-group-addon"><i class="fa fa-external-link-square fa-fw"></i></span>
#Html.TextBox("VanityURL",VanityURL,new { #class = "form-control", #placeholder = "Enter Vanity URL" })
</div>
</div>
</div>
I found some similar posts to mine, but I couldn't find an answer that suits my needs for this.
Problem is as follows:
I have a viewmodel like this:
public class PrefViewModel
{
public SelectList countries { get; set; }
public SelectList Provincies { get; set; }
public ApplicationUser user { get; set; }
public Preference MyPref{ get; set; }
public int mycountry { get; set; }
public int myprovince { get; set; }
}
my cshtml looks like this:
#using (Html.BeginForm("Index","Preferences", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.user.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="control-label col-md-10">
<span class="textvak">
#Html.TextBoxFor(model => model.user.UserName, new { disabled = "disabled", #readonly = "readonly" })
</span>
#Html.ValidationMessageFor(model => model.user.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.user.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="control-label col-md-10">
<span class="textvak">
#Html.TextBoxFor(model => model.user.Email, new { disabled = "disabled", #readonly = "readonly" })
</span>
#Html.ValidationMessageFor(model => model.user.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.user.Unhashed, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.user.Unhashed, new { htmlAttributes = new { #class = "form-control", type = "password" } })
#Html.ValidationMessageFor(model => model.user.Unhashed, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.user.Provincie.Land, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="control-label col-md-10">
#Html.DropDownListFor(model => model.mycountry, Model.countries, new { Name = "ddlLand", id = "ddlLanden", #class = "textvak" })
#Html.ValidationMessageFor(model => model.user.Provincie.Land, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.user.Provincie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="control-label col-md-10">
#Html.DropDownListFor(model => model.myprovince, Model.Provincies, new { #class = "textvak" })
#Html.ValidationMessageFor(model => model.user.Provincie, "", new { #class = "text-danger" })
</div>
</div>
<br />
<table>
<tr>
<td>
<input type="submit" value=#Resources.Wijzig class="btn btn-default" />
</td>
</tr>
</table>
}
and in my controller I try to get the posted PrefViewModel back as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(PrefViewModel TestMymodel)
{
if (ModelState.IsValid)
{
int myCountry = TestMymodel.mycountry;
int myprovince = TestMymodel.myprovince;
}
return View();
}
My problem is that the PrefViewModel TestMymodel never is filled with the values I thought i'm posting back. Even more strange to me is the fact that I do get the Unhashed password back, but all other values are 0 or null.
I can put values inside the PrefViewModel to load the page and that works, but on Posting it's almost entirely empty.
Any ideas?
edit: Would it make any difference that I did change the default model to one that I made up myself? Cause when I Call the Create action for example, I do get the values back in my post (from create offcourse). I'm getting a bit desperate
edit2: this is what was posted:
__RequestVerificationToken:-JYcw0CH2zZ7WrGUiYJM6-R6VxfL41ykTD5EHUjgtyyFcN01AaUU61BYuaRNr4oPdEvDq09aYsOFdb8fObJTXMnTKulADVkGY8CrBG3U71QXw0g7Th86WKl1up4059Zy7mW0SlrWGJpehed586v_5g2
user.Unhashed:Jonas1234-
user.Unhashed:Jonas1234-
ddlLand:1
ddlProvincie:3
(can't add picture with my reputation, so here a link to the full post: http://postimg.org/image/id95wjcxp/ )
Ok, when I change the name of the dropdownlists to the PrefViewModel property name those values get returned correct.
It appears that you have overriden the names of the drop down lists to some values which are different than the property names in your view model. That's why the values are not successfully bound back. Make sure that your input fields respect the same names as the properties on your view model if you want the default model binder to be able to bind them back to the view model.
Also your username textbox has the disabled flag:
#Html.TextBoxFor(model => model.user.UserName, new { disabled = "disabled", #readonly = "readonly" })
so it will not be submitted back to the server. You might need to add an additional hidden field if you want those values to travel back. Or simply use readonly without disabled attribute. Both attributes prevent the user from modifying the value in the corresponding input field but in addition to that the disabled attribute strips it from the POST payload when the form is submitted.
So you may use:
#Html.TextBoxFor(model => model.user.UserName, new { #readonly = "readonly" })