How to make a field required without data annotation - asp.net-mvc-3

I am using the MvcContrib Grid to display a table on the page. I am using a custom column to produce a checkbox on the table so that the user can select multiple rows and submit the form.
I don't want the form to submit unless at least one checkbox has been selected. I could easily write this Javascript myself to enforce the validation, but I wanted to know how I could fit it in with the unobtrusive library supplied with MVC3.
I imagine I just need to set my inputs with the proper classes and attributes and then the scripts (validate and validate.unobtrusive) on the page should pick them up and mark them as needing validation, but I haven't been able to get the right combination thus far.
Here is the input that I am currently generating:
<input type="checkbox"
name="foo"
value="#item.foo"
class="input-validation-error"
data-val-required="Please select an option."
data-val="true" />

Try setting the data-val attributes on the item, then you have to tell jQuery you have new content to re-parse the form via something like:
$.validator.unobtrusive.parse($('#yourForm'));
where form is of course a reference to your form element.
There is also this great posting and jQuery has a few internal adapters you can call:
from http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2
jQuery.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty", "mynotequaltofunction")

From my experience, a commonly overlooked mistake with displaying client-side validation is putting a Html.ValidationMessageFor(lambda) on the page.
Without that, no client-side validation will fire to prevent the form submit and/or display the message that is generated using annotations on the client-side.
Hope this helps.

<div class="editor-field">
<input class="text-box single-line"
data-val="true" data-val-number="The field Qty Available must be a number."
data-val-range="The field Qty Available must be between 0 and 120."
data-val-range-max="120" data-val-range-min="0"
data-val-required="The Qty Available field is required."
id="QtyOnHand" name="QtyOnHand" type="text" value="12" />
<span class="field-validation-valid" data-valmsg-for="QtyOnHand"
data-valmsg-replace="true"></span>
</div>
The tie-in between the data model annotations and the data-val-* attributes should be clear after reading the above code, but it's where the client side validation ties in might not be so obvious. Open the \Scripts\jquery.validate.unobtrusive.js file and search for "data-val". Right away you'll see that the JavaScript uses the data-val-, input- and field-* CSS classes to display/hide validation messages on the client.
The above is taken from this great article, which you might want to read in full.

Related

parsley.js 'fails' when trying to validate checkbox

We are re-designing a site and part of that re-design involves making the site accessible to screen readers and the like. I'm using latest version (2.8.0). Here's what's happening --- validation for all text, select and textarea fields in our forms work perfectly. In order to be accessible, checkbox and radio inputs are wrapped in tags. The html for a set of checkboxes looks like this:
<div class="form-group">
<p id="applicant_type_desc" style="margin-bottom: 6px;"><strong>I am: <span class="text-danger" aria-hidden="true">*</span><span class="sr-only">Required</span></strong> <em class="small">(check all that apply)</em></p>
<div class="checkbox">
<label id="applicant_type_patient_desc">
<input type="hidden" name="applicant_type_patient" id="" value="N">
<input type="checkbox" name="applicant_type_patient" id="applicant_type_patient" value="Y" {checked_applicant_type_patient} aria-labelledby="applicant_type_desc applicant_type_patient_desc" data-parsley-multiple="type" data-parsley-error-message="Please specify whether you are a patient, relative, employee or other.">
A patient
</label>
</div>
followed by more checkbox divs without error messages and ended with an end div for the for form-group wrapper.
If I load the form and click 'submit', all the text fields are validated properly. If I add 'required' to the checkbox above, when 'submit' is clicked nothing happens and the form is submitted with no validation at all.
The same thing happens when I try to validate a radio button set as required.
There is some custom jQuery and parsley code which creates a div to hold all the error messages and transforms the error messages into links to the field id so that a screen reader can follow them and focus on the field in error. But imho, this should have no effect on why the form validation doesn't kick in.
I'm absolutely baffled.
FYI - I tried this using an earlier version (2.0.3) of parsley and the validation actually worked, although all my custom error processing was ignored.
Any insight would be greatly appreciated.
As it turns out, parsley handles the errorswrapper element differently for text, textarea and selects then it does for checkboxes and radio buttons.
The starting wrapper element for text, textarea and select contains the parsley-data-id attribute whereas checkbox and radio button elements contain the parsley-data-multiple attribute whether that was generated by parsley or entered manually in the html.
My code was looking for parsley-data-id and, of course the jquery selector failed and generated an error. A colleague was able to spot this for me while we were looking at the page in chrome inspector. Once i saw the error, making a simple adjustment to the form:error event function allowed everything to work.

Struts 2 XML form validation breaks when new element that does not need validation is added

I am facing an issue that is really hard to debug. I have a JSP page that has some form elements on it that submit to a Struts2 action. I also have a XML form validation file to perform some validation on the submitted fields. The file has the naming convention 'actionName-validation.xml'
This works fine, but when I add a drop down box, outside of the form, the validation now fails. Instead it redirects to a blank page and my breakpoint in my action class is not hit.
Is there a way to turn on some kind of debugging or logging for the validation? Why would adding a tag outside of a form cause this to happen?
Here is the code on the JSP page:
<s:select id="dataSource" name="selectedDataSource" theme="simple" listValue="top"
headerKey="" headerValue="Choose Data" list="dataSources" size="1" />
<div id="forms">
<s:form method="post" action="MyAction" theme="simple">
<p>
<label class="input" for="name"
<span style="color:red;">*</span>
<span>Name</span><br>
<s:textfield theme="simple" name="name" maxlength="11" size="11" />
<br>
<s:fielderror theme="plain"><s:param value="'name'" /</s:fielderror></label>
</p>
<s:submit value="Create New" theme="simple" cssStyle="display: block; clear: left;"/>
</s:form>
</div>
If I remove the <s:select> tag, it works.
Any help would be greatly appreciated it.
EDIT2: I found the problem. I needed a get method for the list that is used to populate the select drop down inside the action that the form submits to.
I had one for the action that initially is called for the page, but when the validation fails and it re-loads that page from the form action class, it tries to re-populate the select drop down and needs a getter there. I feel silly for not finding that sooner. Would be nice if there were some type of logging or messaging of these types of issues.
thanks.
The error you are encountering is not a validation error (handled by the Validation Interceptor), but an error occurred when setting the parameters (raised by the Parameters Interceptor) and for which the Conversion Error Interceptor added a fieldError, which you are not seeing because
your INPUT result lands on a blank page and
you are using theme="simple" on the textfield, which forces you to add <s:fielderror fieldName="dataSource" /> to show it (or <s:fielderror /> to show them all).
Read how the INPUT result works, set your page as the INPUT page, print the errors, then you will discover the problem, that is most likely related to the fact that you've not specified a listKey attribute in your select, that is sending the description instead of the code of the datasource to selectedDataSource, which is probably an Integer.
I found the problem. I needed a get method for the list that is used to populate the select drop down inside the action that the form submits to.
I had one for the action that initially is called for the page, but when the validation fails and it re-loads that page from the form action class, it tries to re-populate the select drop down and needs a getter there. I feel silly for not finding that sooner. Would be nice if there were some type of logging or messaging of these types of issues.

Can't display my own id in apex:inputField in browser

I am very new to apex and just start to study how to add validation on the field. I am not able to do this from set up. In more detail I want to assign an id to apex:inputfield. I read a lot of information in the internet such as using partial id like http://www.kineticgrowth.com/javascript-visualforce-jquery-partial-id-selectors/
However know matter what I add in apex page, it doesn't show up inside the string. Here is my code:
<apex:pageBlock id="pageBlock" ...>
...
<apex:dataTable ... id="transTableBrandPurchase" ">
...
<apex:inputField id="eric_test" value="{!varBla}" required="true" />
when I check the browser in html it gets
<input id="j_id0:j_id6:pageBlock:transTableManufacturerPurchase:0:j_id273" maxlength="255" name="j_id0:j_id6:pageBlock:transTableManufacturerPurchase:0:j_id273" size="20" type="text">
Based on Salesforce reference I should get id="j_xxx:j_yyy ...:pageBlock:transTableManufacturerPurchase:eric_test"
People may say that I can just use "pageBlock:transTableManufacturerPurchase", I cann't because in this page we display then rows and the other rows look like similar:
<input id="j_id0:j_id6:pageBlock:transTableManufacturerPurchase:0:j_id275" name="j_id0:j_id6:pageBlock:transTableManufacturerPurchase:0:j_id275" >
Right now I am working on validation in visualforce page with Jquery.
My approach to assigning ID to elements in VF page is, give ID to all apex elements. Then use chrome inspect element option to find exact ID.
If you are using salesforce any repeat tags , , etc, salesforce will add additional numbering on your ID, to make sure that all elements have unique ID.

why does Razor put validation attributes in #Html.Hiddenfor() helper?

it doesn't make any sense, is there anyway to make this not to act this way?
for
#Html.HiddenFor(model=>model.Id)
I get
<input type="hidden" value="e62fceab-588c-4777-bfe9-8516425a5028" name="Id" id="Id" data-val-required="The Id field is required." data-val="true">
MVC is automatically adding required validation to all non null-able fields. If you don't like this then you can make your id null-able.
It's just an additional layer of server side protection. It's trivial to change an outgoing hidden input with a man in the middle tool like Fiddler.
As for making it optional, there's almost surely a data attribute for that. Alternatively, adding a question mark after the property name in your model should do it.

How to recognaize which ajax form it is in Django?

I have view which takes care of all the Ajax submits from the client side. And to differentiate them by I uses different submit button names such as this one
<input type="submit" value="Send" name="send_message">
Suggested from this question.
The only problem is that from the view side it doesn't seems to carry the name to the server side so I cannot use the following if-statement
if 'send_message' in request.POST:
It works if I send it normally with page fresh. But I want to use it with Ajax.
I came up with a hack that you can add this name with jQuery. Simply by after serializing() your data you then concatenate the name attribute by data += "&send_message"
Then the if statement will work. But it doesn't seems so clean. So I wonder if there's a better way to handle this? Or should I make different views to handle the different Ajax calls I have?
You really should post each form to a different URL.
If not, you could add a hidden input with the name of the form as the value.
<input name="form_name" type="hidden" value="form_1" />
views.py:
form_name = request.POST['form_name']

Resources