JQuery validation based on class? - asp.net-mvc-2

I have a form that will have dynamically created elements, one of those will be of date type. There can also be many fields of this type on my form, all which must be validated.
I am using a strongly typed view in Asp MVC, so the name will change based on various factors. What I would like to do is validate based on a class name instead, since that will be constant for that type of field.
Ie:
<%= Html.TextBox("questionAnswers[" + index + "].AnswerValue", qa.AnswerValue, new { #class = "DateTypeClass" })%>
So then I would need JQuery validation based on the classname DateTypeClass versus the Name.
Any ideas?

In your validation function you could check the value like so:
var dateFieldValue = $(".DateTypeClass").val();
//validate dateFieldValue here
Also you don't have to resort to selecting by class if you don't want to. If no other fields share this validation then you could select by partial id in jquery. That would look like this:
var dateFieldValue = $("[id^=someId]").val();
//validate dateFieldValue here
So you would if set someId on the field and ASP.Net adds some additional stuff to the id it will still select it properly. I don't use ASP.Net MVC so not sure where you are setting the ID (if at all)
Also if you want inline validation you can wireup the onBlur event like so:
$(".DateTypeClass").blur(function(){
//Call field validation function here
});

Related

How to add cross-field validation in Angular 2 with a complex model

Cross-Field Validation in Template Based Forms
Question: Is it possible to create some sort of validation context that spans multiple fields but does not modify the underlying model? If not, is there a better way to do what I'm doing?
Given a model like this and assuming that changing the model is not possible:
export interface IEvent {
location?: {
address: string;
city: string;
country: string;
};
onlineUrl?: string;
}
What is the best way to build a template-based form that will require either all of the location object (address, city, country) to be populated OR the onlineUrl to be populated?
Here is a working Plunk where I have the custom validation working but there are some challenges:
In order to match the model, we need an ngModelGroup around the location fields, but onlineUrl should not be inside that ngModelGroup since it is not part of the location object. Since onlineUrl is not inside the ngModelGroup, it's difficult to come up with a cohesive validation approach. Notice in this example, that we've added a custom validator on the ngModelGroup, that seems to break some basic validation premises - for example, notice that when the fields are invalid that the red highlighting only shows up next to the location field because the custom validator is on the ngModelGroup and onlineUrl is not inside that group.
Typing in the onlineUrl field does not automatically trigger the re-validation since this field is not in the ngModelGroup that has the custom validator on it. In order to make this work I needed to add this binding: (change)="locationGroup.control.controls.address.updateValueAndValidity()" to the onlineUrl field in order to trigger the validation on a field inside the ngModelGroup. This doesn't seem ideal.
Restating the Question: Is it possible to create some sort of validation context that spans multiple fields but does not modify the underlying model?
You can place 'validateLocation' directive up in the top 'form' tag:
<form #myForm="ngForm" (ngSubmit)="save(myForm)" autocomplete="off" novalidate validateLocation>
<fieldset ngModelGroup="location">
Then validate() method gets access to both location and onlineUrl via 'FormGroup.value' and will look like:
if (control && control.value && control.value.location) {
let g = control.value;
if (g.location.address && g.location.city && g.location.country)
return null;
if (g.onlineUrl)
return null;
}
return {validateLocation: false}
Try this plunker. Form.valid would become true when either location or url is captured.

Get the properties of reference pages - Kentico

I have a page where I need to display testimonials, In that page document type I have a field to assign testimonials by using page selection, so It will save the GUID of selected testimonial in the database,
I have used following code to display the description of Testimonial, But is there any other way to get the document fileds by passing the GUID,
One option I can use is write a custom macro.
{% Documents["/Page-Resource/Testimonial/Testimonial"].getValue("Description") #%}
Note: I have used the text/xml type transformation
Well it's not that easy but there is one way and that is to use loops:
r = ""; foreach (i in CMSContext.Current.Documents) {if(i.NodeGUID == "a88f82be-bb76-4b82-8faf-5253209f0f75"){r = i}}; r.Description
Notes:
Use NodeGUID or DocumentGUID based on what you store in your custom field.
Replace the hardcoded guid with something like CMSContext.Current.CurrentDocument.YourDescriptionFieldWithGuid
See the documentation if you have any doubts about K# syntax

Symfony 2.x Form Field Name

When I render a form, form Filed Name is given as an array. For example: search[item], search[keyword] etc. where search is name of the form.
I'm not great on working with forms but I think, the name should be rendered as simply, name="item" or name="keyword".
I've looked at all the documentation, customizing form rendering topic etc. but I can't find any way to change the default behaviour of Symfony form to render form filed name from 'search[item]' to 'item'.
This way, when I ask for the POST data, I can ask simply $this->getRequest()->request->get('item'), as I have to deal with lots of individual parameters.
Help would be great i) To figure out how to achieve what I want. ii) to let me know, why the name is rendered this way. is this the good practice?
Rather than accessing parameters from the Request object, you can bind the Request object to the form.
For example, in your controller method that you post your form to:
namespace Acme\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\Form\MyFormClass;
class MyFormController extends Controller
{
receiveFormAction(Request $request)
{
$form = new MyFormClass();
// you can specify that a route only accepts a post
// request in the routing definition
if ($request->isMethod('POST')) {
// this populates the form object with the data
// from the form submission
$form->bind($request);
if ( ! $form->isValid()) {
throw new \Exception('Invalid form');
}
// an array of the data the format you require
$data = $form->getData();
$data['item'];
$data['keyword'];
// etc.
}
}
}
The above is the way you should be handling forms in Symfony 2, and is how you can leverage the power that the forms component gives you, with validation etc.
Symfony supports multiple forms on a page. They might be instances of the same form or have similar field names. Having the fields for each form all together in an array makes this easy to do.

How to remove a validator from a Select?

I have a form where I need to add/remove validators dynamically. Based on a dropdown selection, other form fields may have different validation rules.
For other kinds of inputs, I've used replace(methodThatCreatesTheInput()) to get rid of a previously added validator. (Not knowing of a better way. Specifically, there doesn't seem to be any way to directly remove a validator from a component...)
With Select, from wicket-extensions, this approach fails with something like:
WicketMessage: submitted http post value [[Ljava.lang.String;#5b4bf56d]
for SelectOption component [8:myForm:targetInput] contains an
illegal relative path element [targetConsortiums:1:option] which does not
point to an SelectOption component. Due to this the Select component cannot
resolve the selected SelectOption component pointed to by the illegal value.
A possible reason is that component hierarchy changed between rendering and
form submission.
The method that creates the Select:
private FormComponent<?> targetSelection() {
Map<Class<? extends Target>, List<Target>> targets = targetService.getAllAsMap();
SelectOptions<Target> propertyOptions = new SelectOptions<Target>("targetConsortiums",
targets.get(Consortium.class), new TargetRenderer());
SelectOptions<Target> consortiumOptions = new SelectOptions<Target>("targetProperties",
targets.get(Property.class), new TargetRenderer());
Select select = new Select(ID_TARGET, new PropertyModel<Target>(model, "target"));
select.add(propertyOptions);
select.add(consortiumOptions);
select.setRequired(true);
select.setMarkupId(ID_TARGET);
return select;
}
(Why use a Select instead of normal DropDownChoice? We want the two types of choices to be clearly separated, as documented in this question.)
Any ideas how to solve this? What I'm trying to achieve is, of course, very simple. Unfortunately Wicket disagrees, or I'm using it wrong.
Wicket 1.4.
I don't know how to do this on Wicket 1.4, but on Wicket 1.5 there is a remove method for validators on FormComponent (see javadoc)

ASP.NET MVC - Display Model Fields without Updating Value

I am currently working on a strongly-typed update view in ASP.NET MVC2. In addition to properties the user can update, there are also some properties that the user should not be able to update, but I would like to display on the page anyway (for example, a created on date).
Here is an example of how I am displaying these non-editable fields:
<td>Created on:</td>
<td><%= Html.DisplayTextFor(model => model.CreatedOn) %></td>
However, when I submit the form and then use a breakpoint on the controller method to see the model object that is being passed to the method via a POST request, the non-editable fields are set to a null or empty value (for example, the CreatedOn date is set to 1/1/0001). The editable fields are being passed back with the correct values. How can I display these non-editable fields while retaining the original value when I post the form back to the controller?
You don't need the original value. If you use UpdateModel (or TryUpdateModel) you can set which properties should be updated. This solution is also a lot safer because you explicitly tell MVC which properties should be updated.
You would need to use a hidden field like so:
<%= Html.HiddenFor(model => model.CreatedOn) %>
This would be in addition to your display field.