jQuery validate required method and textboxes with 0 - asp.net-mvc

I've got a form with two sections. Each section expands by its own radio button, so there's only one visible section at a time. And I use ASP.NET MVC HtmlHelper to generate fields like so:
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type1" id="type1" /> Label1
</label>
<%= Html.TextBox("Field1", Model.IntProperty1) %>
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type2" id="type2" /> Label2
</label>
<%= Html.TextBox("Field2", Model.IntProperty2) %>
I also have two functions so that I could determine, which section is active:
function isType1() { return $("#type1").attr("checked"); }
function isType2() { return $("#type2").attr("checked"); }
Finally, I've got the followind validation methods set up:
Field1: {
required: isType1,
min: 1
},
Field2: {
required: isType2,
min: 1
}
Now, the point is that if I pass empty model to the view, both fields are set to 0 (default for int). Now if the user fills some fields and tries to submit the form, there is validation error, because even though the field in other section is not required, but it has the value - 0, which is not correct since it must be more that 1. How can I overcome this except clearing fields in hidden sections before form submission?
UPDATE. I guess I need some kind of conditional validation method.

If you can build it in, the required method takes a callback, so maybe you can build in the zero null check into the required validator via: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-callback
HTH.

Related

Angular 2 reactive form validation for non mandatory field

I am working on reactive form like In my reactive form having 3 fields but in which 2 are mandatory and one is non mandatory but it has validation like if user enter a string in respective field it has minimum character limit example 10 character. but i faced issue when user has enter string it is showing error but submit button is not going to disable.
return FormBuilder.group({
'surveyDueDate': ['', Validators.required],
'rfsDueDate': [null, Validators.required],
'comment': [null]
});
<form (ngSubmit)="submit(form)" #form="ngForm">
<div>
Survey date:
<input name="surveyDueDate" [(ngModel)]="surveyDueDate">
</div>
<div>
Due Date :
<input name="rfsDueDate" [(ngModel)]="rfsDueDate">
</div>
<div>
Gift shipping address:
<input name="comment">
</div>
<button type="submit" [disabled]="form.invalid">Register now!</button>
</form>
thanks in advance.
In your component listen for the particular field changes. For example,
this.form.controls["comment"].valueChanges().subscribe((commentValue)=>{
if(commentValue && commentValue.length>10 && this.form.invalid===false){
this.form.controls["comment"].setErrors({invalid:true});
} else {
this.form.controls["comment"].setErrors(null);
}
});

Rails Simple Form single checkbox twice in querystring

I have a search form which I return to after searching, to be able to refine the search. I just added a checkbox to that form.
In the view:
<%= f.input :available_tomorrow, as: :boolean, label: false,
inline_label: t('public.search.form.available_tomorrow.label'),
input_html: { name: :available_tomorrow, value: params[:available_tomorrow],
id: :available_tomorrow } %>
In the model:
attr_reader :available_tomorrow
HTLM produced:
<div class="form-group boolean optional search_available_tomorrow">
<input name="available_tomorrow" type="hidden" value="0">
<label class="checkbox">
<input class="boolean optional" id="available_tomorrow" name="available_tomorrow" type="checkbox" value="1">
Available tomorrow
</label>
</div>
When I check the box, all search parameters appear fine in the url querystring but that one:
&available_tomorrow=0&available_tomorrow=1
Looks like the value property of both field is sent, and neither changes. If I uncheck the box, I only get &available_tomorrow=0 in the querystring. The second part is only added if the checkbox is checked.
Everything works as intended (the search does return the right results depending on the checkbox state, the checkbox is in the right state when the search form is updated). But that querystring is ugly with both available_tomorrow parameters, looks like the first one should never appear. Ideas?
This is normal behavior for a form with a checkbox when you POST the form: If the checkbox is not checked, only the hidden field with value 0 is sent with the formdata. If the checkbox is checked, the input with the value 1 is also sent.
The hidden field for the checkbox is always sent, this is because otherwise no value for the checkbox would be sent.
Long story short: don't mind the querystring in your search url, nobody will ever look at them. :)

Handling hidden field in multiple forms in Mvc 4.0

I am having multiple forms in one page and that page inherits one single model.Every form submission requires a common value. So, common value is stored in hidden field. The hidden field is kept global i.e outside of all the forms but my problem is whenever I submit form, that hidden field is coming to be empty.The hidden field is #Html.HiddenfieldFor(m=>m.FkId) and this FkId is of string type proprty in model i.e public string FkId{get;set;} .Can somebody please guide me how to handle this situation. If I keep hidden field in one of the forms then , it is coming in controller but only for that form submission where I have kept it. But I want that property to be set once and can use in all the form submissions.Please help me. How can I sort out this problem
Some related code
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
#using (Ajax.BeginForm("Evaluation","SaveTab1"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab1" value="Submit" onclick="CheckUser();"/>
}
</div>
<div id="tabs-2">
#using (Ajax.BeginForm("Evaluation","SaveTab2"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab2" value="Submit" />
}
</div>
<div id="tabs-3">
#using (Ajax.BeginForm("Evaluation","SaveTab3"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab3" value="Submit" />
}
</div>
</div>
<script type="text/javascript">
function DisplayMessage(Json)
{
alert( $("#fkID").val(Json.hdn));
// and Alert is showing the value
$("#fkID").val(Json.hdn);
}
</script>
In the Controller I have:
public ActionResult SaveTab1(Model obj)
{
tbl ob =new tbl();
ob.FkId=Obj.fkID;
// after saving, I return
return json(new{hdn=Obj.fkID})
}
public ActionResult SaveTab2(Model obj)
{
tbl ob =new tbl();
ob.FkId=Obj.fkID;
//after saving, I return
return json(new{hdn=Obj.fkID})
}
Similar for tab three, but unfortunately the hidden filed only comes for first form submit. Then I return value to view by json and again set the hidden field property but then it comes null for second form.Please help
First of all, your View does not inherit the Model, it is strongly-typed to the type of your Model. These two are completely different.
But, to answer your question, there's no such a thing as a global hidden field. Fields are not variables. If you want a field to be posted to your Controller, you need to put it inside the form. If you have multiple forms in your View, then you'll have to put the same hidden field inside all the those forms. So, you need to put #Html.HiddenFor(m => m.FkId) inside all the forms in your View.
UPDATE: By the way, it's not Html.HiddenFieldFor, it's Html.HiddenFor.
I have solved the problem. Instead of taking same field in all the forms which was not working, I have taken a unique and different Hidden field properties and after on seperated success function of each form and set the every hidden field a value in success method.

Is This Unexpected Behavior for the CheckBox HtmlHelper?

My view page contains a search-by-example form with the following checkbox code:
<td>
<label for="HasProcessErrors">Has Errors:</label>
<%= Html.CheckBox("HasProcessErrors", crit.HasProcessErrors) %>
</td>
The crit object HasProcessErrors property is a boolean whose initial value is false. When I view the source of my rendered page, I see that the helper has generated the following HTML:
<td>
<label for="HasProcessErrors">Has Errors:</label>
<input id="HasProcessErrors" name="HasProcessErrors" type="checkbox" value="true" /><input name="HasProcessErrors" type="hidden" value="false" />
</td>
Have I used the CheckBox helper incorrectly here, or is something odd going on? It seems like it should generate an input of type checkbox with checked = "".
Thanks for any ideas.
Yes this is correct.
The semantics of a checkbox are a little bit different from what you may think; instead of posting a value indicating its checked/unchecked state, a checked checkbox posts whatever is in its ‘value’ attribute, and an unchecked checkbox posts nothing.
As there is also a hidden field with the same name, if you debug your form submit, you will find a checked checkbox has the value 'true,false' whilst an unchecked box has the value 'false'
You can determine if a checkbox is checked by testing if it contains 'true'.
public ActionResult(FormCollection form)
{
bool checked = form["checkbox_id"].ToString().Contains('true');
}

HTML.CheckBox(string) evaluates to two HTML elements instead of one

The code
<%=Html.CheckBox("SendEmail") %>
evaluates to two HTML elements when it's rendered
<input id="SendEmail" name="SendEmail" type="checkbox" value="true" />
<input name="SendEmail" type="hidden" value="false" />
Is this by a bug? Or by design? If it's by design, why?
I was having some trouble this morning with retrieving selected values from a checkbox group in my MVC app. I sent this out to my team and thought I'd share it with everyone else.
When posting back values for checkboxes, the standard behaviour of all browsers is to completely leave out un-checked checkboxes from the post back. So if you have a checkbox that isn’t checked then nothing shows up for this in Request.Form. This is a fairly well-known phenomenon that most developers account for.
In ASP.Net MVC when you use Html.Checkbox, it attempts to get around this and ensure that you have a value posted back (in this case ‘false’) for un-checked checkboxes. This is done by adding a hidden field containing the value ‘false’.
Eg.
<%= Html.CheckBox("Sites", s.Selected, new { value = s.Value })%>
Produces the HTML
<input id="Sites" name="Sites" type="checkbox" value="1" /><input name="Sites" type="hidden" value="false" />
This is all good and well, until you attempt to use checkbox groups. That is more than one checkbox with the same name where the values are sent back in a single comma separated string.
MVC can split this string up for you automatically if you define the value as an array (string[] Sites).
Here’s the view code:
<% foreach(var s in Model) { %>
<li><%= Html.CheckBox("Sites", s.Selected, new { value = s.Value })%>
<label><%= s.Name %></label>
</li>
<% } %>
The appropriate controller action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int Id, string Name, string SubmissionUrl, string[] Sites)
Unfortunately, because the Html.Checkbox produces this hidden field value as well, the resulting array contains not only values for the selected checkboxes but also ‘false’ for every un-checked checkbox. You get an array that looks something like this:
[0] 'false'
[1] 'false'
[2] '110'
[3] '50'
[4] 'false'
Where 'false' is for checkboxes that are not selected, and integers are the values for the checkboxes that are selected.
This can throw your code out quite a bit if you have only integers for the values of your checkboxes and want to define the result as an array of integers, like so:
public ActionResult Edit(int Id, string Name, string SubmissionUrl, int[] Sites)
Which results in an exception being thrown because it can’t convert the string value ‘false’ to an integer.
The solution is very simple, just avoid Html.Checkbox and manually create the checkboxes in your view code like this:
<% foreach(var s in Model) { %>
<li><input type="checkbox" name="Sites" value="<%=s.Value%>" <% if (s.Selected) { %>checked="checked"<% } %> />
<label><%= s.Name %></label>
</li>
<% } %>
Hope this helps someone else!
When all else fails, read the source code. :) this is from HtmlHelper.cs:
// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.
I'm not exactly sure how useful that is, but at least you know the intention.
I think I found something on the web that is directly related to my question.

Resources