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>
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 :)
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>
Can somebody tell me why "This field is required" and "Please insert database name" are being displayed instead of just "Please insert database name"?
This is my model :
public class InstallViewModel
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Please insert database name")]
public string DatabaseName { get; set; }
and this is my view :
<div class="input-group">
<span class="input-group-addon">Database</span>
#Html.TextBoxFor(w => w.DatabaseName, new { #class = "form-control", placeholder = "Database name" })
</div>
#Html.ValidationMessageFor(w=> w.DatabaseName)
Thank you.
EDIT:
Can you see the image attached ? I have some problems uploading images.
The view is a partial view and this is the whole partial view:
#Html.ValidationMessageFor(w => w.DatabaseName)
<div class="input-group">
<span class="input-group-addon">Database</span>
#Html.TextBoxFor(w => w.DatabaseName, new { #class = "form-control", placeholder = "Database name" })
</div>
<br />
#Html.CheckBoxFor(w => w.UseWindowsAuthentication, new { #checked = "checked" }) Use Windows Authentication<br /><br />
<div class="wizard-sqlauth" style="display: none">
<div class="input-group">
<span class="input-group-addon">User name</span>
#Html.TextBoxFor(w => w.UserName, new { #class = "form-control", placeholder = "User name" })
</div>
#Html.ValidationMessageFor(w => w.UserName)<br />
<div class="input-group">
<span class="input-group-addon">Password</span>
#Html.PasswordFor(w => w.Password, new { #class = "form-control" })
</div>
#Html.ValidationMessageFor(w => w.Password)
</div>
DatabaseName is "Required" and your input is empty. (There is only placeholder text)
Are you calling jquery validation "manually" anywhere in javascript, i.e.
$('#myform').valid() ?
That would trigger the default value for the required rule ("This field is required."), and would append it as a label after the input, which is exactly the behavior your are experiencing.
If you really need to use both (MVC's Unobstrusive validation + jQuery validation) you can configure jquery validation to ignore certain fields, for example
$('#myform').validate({
ignore: '#databasefieldId'
});
You have applied the RequiredAttribute attribute to a property to the property DatabaseName which implies that the property must contain a value.
A validation exception is raised if the property is null, an empty string (""), or contains only white-space characters.
You just add #Html.ValidationMessageFor(w=> w.DatabaseName) in the top of div. This will show the summary.