How to validate your form using bootstrap in asp.net mvc? - c#

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.

Related

Client side & Server side validations in ASP.NET MVC

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

Umbraco Member - How to set a custom mandatory property to be required in the registration form?

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 :)

How can call model in layout in mvc 4 razor

I want to call model in layout for use a validation in empty text field for return a error to gust user if any fields are empty. i have a code layout
#using (Html.BeginForm("Sending", "Home"))
{
<form method="post" id="contactfrm" role="form">
<div class="col-sm-4">
<div class="form-group">
<label for="name">Name</label>
#Html.TextBoxFor("Name", null, new { id = "name", #class = "form-control", placeholder = "Enter name", title = "Please enter your name (at least 2 characters)" })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
<label for="email">Email</label>
#Html.TextBoxFor("Email", null, new { id = "email", #class = "form-control", placeholder = "Enter email", title = "Please enter a valid email address)" })
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="comments">Comments</label>
#Html.TextArea("Comment", null, new { id = "comments", #class = "form-control", TextMode = "MultiLine", Columns = "3", Rows = "5", placeholder = "Write you message here...", title = "Please enter your message (at least 10 characters)", Style = "resize:none" })
#Html.ValidationMessageFor(model => model.Comment)
</div>
<button name="submit" type="submit" class="btn btn-lg btn-primary" id="submit">Send Your Message</button>
<div class="result"></div>
</div>
</form>
}
i want to call sending.cs model for use in #Html.ValidationMessageFor(model => model.Name)
How can i call Model in layout?
Thank you
add your model to your View page like this
#model nameOfModel
and use it like this
#Html.ValidationMessageFor(model => model.Name)
and if you want to use only a porperty of it do it like this
#Model.nameOfproperty

How to validation from Microsoft sql sever

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>

MVC4 Remote Validation Not Receiving Parameter Value

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>

Categories