I need to check whether all fields are filled while clicking insert button.
This is my view:
<body>
<form name="form1">
<h2>MEDICATION</h2>
<div class="med">
<pre>
<label>Patient code</label> <input type="text" id="pat" name="ptcode" size="25" value="" /> <label>ICD10</label> <input style="width:85px;height:30px;" type="text" name="icd10" value=""> <button style="height:30px;width:59px;" name="search" onclick="openicd()";>search</button><br />
<label>Medication</label> #Html.DropDownListFor(Model => Model.medication, Model.medication,"Select Medication", new { style = "width:200px; height :30px" }) <button style="height:30px;"onclick="openmedication()";>search</button> Prescription Date <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">
<label>Strength</label> #Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" }) Start Date <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""> End Date <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""><br />
<label>Form</label> #Html.DropDownListFor(Model => Model.form, Model.form, "Select form", new { style = "width:200px; height :30px" }) Renewal Date <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""><label> Days Supply</label> <input type="text" style="width:85px;height:30px;" name="supply" value=""> <br />
<label>Route</label> #Html.DropDownListFor(Model => Model.route, Model.route, "Select route", new { style = "width:200px; height :30px" }) <label>Pharmacy</label> #Html.DropDownListFor(Model => Model.pharmacy, Model.pharmacy, "Select Pharmacy", new { style = "width:200px; height :30px" })<br />
<label>Dose</label> #Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px" })
</pre>
</div>
</form>
<hr />
<div class="wrapper">
<button class="button" style="height:30px;" id="a" >Insert</button> <button class="button" style="height:30px;" id="b">Update</button> <button class="button" style="height:30px;" id="c">Delete</button>
</div></body>
</html>
The best way is adding model Validations in Models
i don't know how your model look like assuming
public class Meditation
{
[Required]
public int id{get;set}
[Required]
public int name{get;set;}
}
using System.ComponentModel.DataAnnotations; should be added
or you can simply use required in form
<input type="text" style="width:85px;height:30px;" name="supply" value="" required>
#Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px", #required="true"})
You can use your model for validation
public class Example {
public int id { get; set; }
[Required]
public string name { get; set; }
}
view more - Microsoft Docs
Related
I am working on captcha authentication. I want to get user entered captcha value in controller's Index method. Below is my cshtml file code
#{
ViewData["Title"] = "Home Page";
}
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br/>
<button class="button" type="submit">Login</button>
<br />
</div>
When user entering captcha value in txtCapValue and click submit button I need that value in controller. Here is my controller
public IActionResult Index()
{
randnumber = RandomString(6);
ViewData["captcha"] = randnumber;
return View();
}
how can I get txtCapValue input control value when user click on submit button ?
One of the easy ways using the Form Tag Helper:
<form asp-controller="Controller_Name" asp-action="Captcha" method="post">
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button class="button" type="submit">Login</button>
<br />
</div>
</form>
And on the server side:
[HttpPost]
public IActionResult Captcha(string cap)
{
... using the `cap`
return View("Index");
}
I want to get user entered captcha value in controller's Index
method.
There are two options, you can try:
Option1: use Form Tag Helper
Index method:
public IActionResult Index(string cap)
{
ViewData["captcha"] = 6;//do your staff
return View();
}
Index view:
<form method="get" asp-action="Index">
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button class="button" type="submit">Login</button>
<br />
</div>
</form>
Option 2: use ajax
Index method:
public IActionResult Index(string cap)
{
ViewData["captcha"] = 6;
return View();
}
Index view:
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button id="buttonDemo1" class="button" type="submit">Login</button>
<br />
</div>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo1').click(function () {
var cap = $("#txtCapValue");
$.ajax({
type: 'GET',
url: '/Home/Index',
data: cap
});
});
});
</script>
}
result:
I have this control that is hidden and the user need to check the input control for it to be show. I am getting the model fill with data and I wanted to see how I can only get data in the controller if it is selected ?
View
<input type="checkbox" value="91" name="chkProduct">
<label>Other</label>
<input type="hidden">
<input type="hidden" asp-for="Other">
<div id="sourceSection_91" style="">
<div class="row" id="ddRow_6" data-source="sourceSection_91">
<div class="col-md-11 !important">
<div class="form-group">
<label class="control-label source-label">Other</label>
<input class="form-control" id="enteredOtherSource" name="enteredOtherSource[0].Other" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="enteredOtherSource[0].Other" data-valmsg-replace="true"></span>
<input value="91" data-val="true" data-val-number="The field SourceId must be a number." data-val-required="The SourceId field is required." id="SourceId" name="enteredOtherSource[0].SourceId" type="hidden">
</div>
</div>
<div class="col-md-1 deleteBtn">
</div>
</div>
Model
public class OtherSourceModel
{
public int SourceId { get; set; }
public string Other { get; set; }
}
Controller
foreach (var ordermaterial in model.enteredOtherSource)
{
ProjectMaterialUse _SelectedOtherProjectMaterial = new ProjectMaterialUse();
_SelectedOtherProjectMaterial.Source = new Values();
_SelectedOtherProjectMaterial.Source.Value = ordermaterial.SourceId;
_SelectedOtherProjectMaterial.Other = ordermaterial.Other;
_SelectedOtherProjectMaterial.IntendedUse = new Values();
_SelectedOtherProjectMaterial.IntendedUse = model.selectedIntendedUseId;
_permissionrequestWeb.SelectedProjectMaterial.Add(_SelectedOtherProjectMaterial);
}
Model property which I intend to use inside two forms
public class TestModel
{
[Display(Name = "Terms Accepted")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You need to accept terms and conditions to proceed!")]
public bool TermsAccepted { get; set; }
}
view Page
<form id="form1">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted, new { #id = "chk1" })
</div>
<div class="col-md-3">
<input type="submit" id="button1" onclick="return isFormValid('form1');" value="Submit Form 1"/>
</div>
</div>
</form>
<form id="form2">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted, new { #id = "chk2" }) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted)
</div>
<div class="col-md-3">
<input type="submit" id="button2" onclick="return isFormValid('form2');" value="Submit Form 2"/>
</div>
</div>
</form>
When this UI is rendered on the page, checkbox inside the 1st form do contains attributes for RangeDataAnnotation while checkbox inside 2nd form doesn't have any attributes for data annotation. So this results into 2nd form doesn't throw any validation on submission.
Html of checkboxes which get rendered on UI
Inside form 1:
<input name="TermsAccepted" class="input-validation-error" id="chk1" aria-describedby="TermsAccepted-error" type="checkbox" value="true" data-val="true" data-val-range-min="True" data-val-range-max="True" data-val-range="You need to accept terms and conditions to proceed!">
Inside form 2:
<input name="TermsAccepted" id="chk2" type="checkbox" value="true">
Any suggestions to make this work in both forms?
I have following code on my view.
This HTML code is used for search in website.
This view is not strongly typed view, so I can apply use DataAnnotation through model.
What is best view to validate that, this textbox should accept only alpha numeric characters?
HTML
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" placeholder="search" class="fullwidth" onkeypress="return BlockingHtml(this,event);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
Javascript
function BlockingHtml(txt) {
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}
Model:-
[StringLength(100)]
[Display(Description = "Name")]
[RegularExpression("(/[^a-zA-Z 0-9\n\r.]+/g", ErrorMessage = "Enter only alphabets and numbers of Name")]
public string Name{ get; set; }
Updated:-
View:-
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" id="txt" placeholder="search" class="fullwidth" onkeypress="BlockingHtml(this);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
function BlockingHtml(txt) {
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" placeholder="search" class="fullwidth" onblur="return BlockingHtml(this,event);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
Changed event onkeypress to onblur.
I have this in my Web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
My view model:
public class CustomerViewModel
{
public Guid Id { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
}
My view:
#using (Html.BeginForm(MVC.Customers.Edit(), FormMethod.Post, new { id = "edit-customer" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
...
</div>
}
And this is how the "form-group" div gets rendered:
<div class="form-group">
<label class="control-label col-md-2" for="FirstName">First Name</label>
<div class="col-md-10">
<input id="FirstName" class="form-control text-box single-line" name="FirstName" value="" type="text" data-val-required="The First Name field is required." data-val="true">
<span class="field-validation-valid text-danger" data-valmsg-replace="true" data-valmsg-for="FirstName"></span>
</div>
</div>
And I'm loading the jQuery scripts in this order:
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui-1.10.4.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
The form is shown using an ajax call when a button is clicked. It is also submitted with ajax. This all works fine when I'm not doing any validation. I added validation and I can't get it to trigger before the ajax call. Here's what I'm doing in the click handler that submits the form:
var formToSubmit = $('#' + attrData.formIdToSubmit);
if (!formToSubmit.valid()) {
return false;
}
formData = formToSubmit.serialize();
...
I expect formToSubmit.valid() to trigger the validation and return false when nothing is entered in the FirstName field. In practice it returns true and then validation fails on the server, ModelState.IsValid returns false as expected. In looking through the jQuery validation docs it looks like it expects a required attribute, like this:
<input id="FirstName" class="form-control text-box single-line" name="FirstName" value="" type="text" data-val-required="The First Name field is required." data-val="true" required>
If I use dev tools to add that and then click the submit button then the call to formToSubmit.valid() returns false as expected, however the error message doesn't end up in the span created by #Html.ValidationMessageFor, it ends up in a newly added label that looks like this:
<label for="FirstName" class="error">This field is required.</label>
What am I doing wrong?
Here is how I ended up fixing it:
var formToSubmit = $('#' + attrData.formIdToSubmit);
formToSubmit.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(formToSubmit);
if (!formToSubmit.valid()) {
return;
}
formData = formToSubmit.serialize();
...