Spring mvc tag question - spring-mvc

What is the significance 'label' and 'path' in the spring mvc jsp tag:
form:label path="someName"

label simply defines the text of the field within the page, for example:
<form:select path="dataVisArray"><br />
<form:option label="Select..." value=""/>
<form:options items="${dataVisArray} itemLabel="label" itemValue="value"/>
</form:select>
shows a dropdown, where the first element is "Select..." and the rest is defined in ${dataVisArray}
path links to a form backing object where you can save the input. In the example above, there would be a variable called "dataVisArray" within the backing object to save the value of the selected item once the form is submitted.

The label attribute is for displaying text corresponding to the form element for which we are using the label attribute
<label for="FirstName" >First Name :</label>
For Path attribute can be also used in validation of form element by jquery
<form:input path="name" id="name" name="name"/>
The path value name then can be used for validation purpose:
$("#ajaxForm").validate({
rules: {
name: {
required:true,
minlenght:3
},
messages: {
name : {
required : 'Enter Username',
maxlength :'Not more than 30 Charachters',
minlength :'Should be more than 3 characters'
},
Hope this helps.

In Spring MVC JSP tag lable signifies the value to be displayed as part of the tag and path is used to signify path to property for data binding.
<form:label path="company"> Enter company name: </form:label>

Related

Strange behavior of ASP.NET MVC Razor engine with unobtrusive validation attributes

I've just faced a really strange behavior of Razor engine regarding adding unobtrusive validation attributes to inputs in forms. In some cases attributes are not added.
So, I have two similar forms on the same page with similar input elements. They must be submitted to different url's.
From model side, I have a few DataAnnotations Attributes, applied to properties to have a client-side validation.
Here is my a bit simplified code of ViewModel:
public class ApplicantPersonalInfo
{
[Required]
[Display(Name = "First Name")]
[StringLength(20, MinimumLength = 2)]
[RegularExpression(#"^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$", ErrorMessage = "First Name is in incorrect format")]
public string FirstName { get; set; }
}
Now I want to create two forms. For every of them action url can differ dynamically (I submit them using ajaxSubmit from jQuery Form Plugin), that's why I decided not to use Html.BeginForm helper method, instead creating them with simple <form> tag. So my code is:
<form id="form1">
#Html.TextBoxFor(m => Model.FirstName, new { id = "firstName1" })
</form>
<form id="form2">
#Html.TextBoxFor(m => Model.FirstName, new { id = "firstName2" })
</form>
And the most interesting is the resulting html code:
<form id="form1">
<input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 2 and a maximum length of 20." data-val-length-max="20" data-val-length-min="2" data-val-regex="First Name is in incorrect format" data-val-regex-pattern="^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$" data-val-required="The First Name field is required." id="firstName1" name="FirstName" type="text" value=""/>
</form>
<form id="form2">
<input id="firstName2" name="FirstName" type="text" value=""/>
</form>
See? All those validation attributes are not applied to the second input!
BUT if the form is generated using Html.BeginForm, like this:
#using (Html.BeginForm("NotExistingController", "NotExisitngAtion", FormMethod.Post, new { id = "form1" }))
{
#Html.TextBoxFor(m => Model.HomeOwner.FirstName, new { id = "firstName1" })
}
<form id="form2">
#Html.TextBoxFor(m => Model.HomeOwner.FirstName, new { id = "firstName2" })
</form>
the resulting html code is with attributes in both inputs:
<form action="/NotExisitngAtion/NotExistingController" id="form1" method="post">
<input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 2 and a maximum length of 20." data-val-length-max="20" data-val-length-min="2" data-val-regex="First Name is in incorrect format" data-val-regex-pattern="^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$" data-val-required="The First Name field is required." id="firstName1" name="FirstName" type="text" value="" />
</form>
<form id="form2">
<input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 2 and a maximum length of 20." data-val-length-max="20" data-val-length-min="2" data-val-regex="First Name is in incorrect format" data-val-regex-pattern="^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$" data-val-required="The First Name field is required." id="firstName2" name="FirstName" type="text" value="" />
</form>
I'm really confused by this behavior. And I've tried - you can add as much forms as you want using Html.BeginForm - every of them will have set of validation attributes; but if you add >1 form using simple <form> tag, starting from the second one attributes are missing.
So am I missing something or it's a bug in Razor engine?

Html.CheckboxFor vs Html.EditorFor vs straight HTML?

I'm using a template with custom CSS (.less) for checkboxes (making them appear as "Yes|No", "On|Off", etc.)
Using #Html.CheckboxFor(model => model.BooleanProperty, new { #class="custom-switch" }) results in a checkbox not appearing, at all.
So I got to digging around, found many questions on here with similar issues, but none of the solutions worked for me so far. The solution I'm currently working on is to use a custom EditorFor template. This is rendering the checkbox correctly, however, what I'm experiencing is that if the slider is switched to "NO", it's passing across to the controller as null instead of false, and if it's switched to "YES" it's passing across to the controller as "on".
I know that Html.CheckboxFor renders a checkbox element followed by a hidden input element. What purpose does this serve? Following are rendered HTML from the two methods as well any questions pertaining to that specific :
Straight HTML for Checkbox
::before ::after
When this is passed to the controller, why is the value of BoolProperty "true,false"?
#Html.CheckboxFor(model => model.BoolProperty, new { #class="custom-switch" })
<input checked="checked" data-val="true" data-val-required="The BoolProperty is required." id="BoolProperty" name="BoolProperty" type="checkbox" value="true" class="custom-switch">
<input name="BoolProperty" type="hidden" value="false">
What purpose does the hidden input field play? If I remember right, only the first "BoolProperty" named value would actually be passed to the controller anyways. I can't find anything that would suggest that one updates the other when the value changes, and through testing, I've noticed that the value does not change.
#Html.EditorFor(model => model.BoolProperty, new { #class = "custom-switch" })
<input type="checkbox" checked name="BoolProperty" class="custom-switch">
<label>::before ::after</label>
Why would this pass across the values of "on" or null to the controller? Why not true and false?
The Boolean Editor Template
#model Boolean?
var isChecked = ViewData["checked"] != null && ViewData["checked"].ToString() == "true";
<input type="checkbox" checked="#(isChecked ? "checked" : string.Empty)" name="#name" class="#ViewData["class"].ToString()" />
<label class="lbl"></label>
The hidden field is there to force the field to be included in the form POST even when nothing is checked. Without it, the field is omitted altogether, per the standard. You wouldn't know the difference between a "false" value or a non-existent field.
http://www.w3.org/TR/html401/interact/forms.html
As far as why it uses "on" vs "true", that is something you can control yourself. If you want true/false instead of on/off, use that. "on" is just a default, but not required.
<input type="checkbox" class="checkbox" name="BoolProperty" value="true" />
<input type="hidden" class="checkbox" name="BoolProperty" value="false" />
About the hidden field
I can't find anything that would suggest that one updates the other
when the value changes, and through testing, I've noticed that the
value does not change.
No, it doesn't change. The browsers, then a checkbox is not checked, don't submit anything using that name. So, the hidden propose is to submit the value "false" (with the same name) when the checkbox isn't checked.
When the checkbox is checked (as you said) the posted value is "true,false" (first the value of the checkbox and then the value of the hidden). The MVC binder deals with this string to convert it to true value setting it to the BooleanProperty.
About the on value
It is the default value for the checkbox. See here.

Retun list of checkboxes using thymeleaf

<p th:each="accommodationCategory,accommodationCategoryStat : ${accommodationCategoryList}" >
<input type="checkbox" th:field="*{accommodationCategoryList[__${accommodationCategoryStat.index}__].valid}" />
<label th:text="*{accommodationCategoryList[__${accommodationCategoryStat.index}__].name}">label</label>
</p>
AccommodationCategory class has two attribute valid and name. The form return list of AccommodationCategory. I can fill AccommodationCategory's valid attribute from checkbox, I want to fill name attribute using ${accommodationCategory.name} not from user input. I can't fill accommodationCategory's name attribute when post form.

Spring MVC and html input

In Spring 3.1 Web MVC form I am using following field take the date from datepicker and the field defined in form as String. I am getting all the values but I am not getting the date field.
First Try
<form:input id="fromDate" class="mydate" path="fromDate" size="10" maxlength="10" />
<script type="text/javascript">
Spring.addDecoration(new Spring.ElementDecoration({elementId : 'fromDate', widgetType : 'dijit.form.DateTextBox', widgetAttrs : {promptMessage: 'Enter From Date', invalidMessage: 'Please enter valid From Date', required: false, constraints: {datePattern : 'dd/MM/yyyy', required : false}, datePattern : 'dd/MM/yyyy'}}));
</script>
Second Try
<input id="toDate" class="mydate" path="toDate" size="10" maxlength="10" />
<spring:bind path="schemeQuantity.toDate">
${status.value}
</spring:bind>
<script type="text/javascript">
Is it possible to use simple HTML input tag and bound with Spring MVC.
Yes it is possible to use simple html input tag.
In the form tag add a commandName attribute like this
<form:form commandName="attribute" name="createForm" id="createForm" acceptCharset="UTF-8" method="post" action="create">
Now in your controller class add #ModelAttribute like this.
#RequestMapping(value="create" , method=RequestMethod.POST)
public String createAttribute( Model model , #ModelAttribute YourPojoClass attribute,Errors errors)

jQuery Validation Engine - Required Field using regular expression

I am using jQuery Validation Engine in asp.net form. How do I validate a field (required) using a regular expression?
http://www.position-relative.net/creation/formValidator/
jQuery(document).ready(function () {
// binds form submission and fields to the validation engine
jQuery("#aspnetForm").validationEngine('attach', {
'custom_error_messages': {
// Custom Error Messages for Validation Types
'.reqSomeField': {
'required': {
'message': "Please enter Some Field."
}
}
}
});
});
What have you tried thus far?
But here's something that might help you get started. It's from the docucmentation.
custom[regex_name]
Validates the element’s value to a predefined list of regular expressions.
So first you'd need to create your custom regex in the jquery-validation-engine.js file, then call it in the form field. The syntax, in the form field, would be something like this:
<input value="someone#nowhere.com" class="validate[required,custom[email]]" type="text" name="email" id="email" />
Have you tried simply adding this class to the form fields?
<input value="" class="validate[required]" type="text" name="email" id="email" />
That doesn't do any validation other than force the user to put SOMETHING in the field. However, they could enter $$$ into the field, and the form would see that as valid. If you're doing inline validation, and using this plugin in particular, you might want to use the existing validation options for email addresses, something that has letters and numbers but no punctuation, a numbers-only field, et cetera. The pre-existing options are all listed in the documentation.

Resources