I'm using ASP.NET MVC and I have jQuery, jQuery validate, jQuery validate.config, jQuery validate unobtrusive, unobtrusive ajax and other libraries in my bundle. I have a form in my page and has some fields inside of it. It has a button of type button and when the user clicks the button I'm trying to do some stuff and then do a $(form).submit(), which I want it to be intercepted by the submithandler in the jQuery validate method and instead of submitting the form it will do a ajax post to my server. The reason I want to use the jQuery.validate method is that I have a lot of conditional required fields and other validations inside the form. But for some reason the jQuery validate is not executing/firing at all and the form is getting submitted instead of being intercepted by the submit handler. I have no idea why its not working if I setup everything correctly. Here is my call of the jQuery validate method. I never see the alert saying is good.
$('form[name="submitCheckoutForm"]').validate({
debug: true,
rules: {
"Password": {
required: true
}
},
submitHandler: function (form) {
//actions.SubmitCheckout();
alert('is good');
return false;
}
});
If you're using the Unobtrusive Validation plugin, then you cannot also call jQuery Validate's .validate() method.
Why?
The Unobtrusive Validation plugin automatically constructs the .validate() method based on the various data attributes in your form.
The jQuery Validate plugin does not allow the .validate() method to be called more than once on the same form. So since you're already using Unobtrusive Validation to construct .validate(), your other call to .validate() will be totally ignored.
Please use the required attribute instead
<input type="password" required>
Related
I have an ASP.NET web form with validators that are disabled. I want to enable validators only AFTER Submit button is clicked and based on if the control is visible or not.
Here is my function:
protected void Submit_Click(object sender, System.EventArgs e)
{
if (ddlSite.Visible){
rfvSite.Enabled = true;
base.Validate();
} else {
rfvSite.Enabled = false;
}
The above code is working fine. But now I want to check if page is valid or not. If the page is Valid then I want to process the form. I don't know how to do this.
You have multiple options:
Try to split your controls into multiple validation groups, which will only validate the controls in a specific group upon submit.
Write your own custom validator. A custom validator can declare a client validation function and a server validation function. Creating a custom validator is well-documented.
As StevieB mentioned, if you hide the controls server-side, the validators won't be fired. If the decision to hide them is made on the client, that's more difficult.
Hook into the client-side validation functions and manipulate the validators. This can be difficult and may require changing internal ASP.Net scripts. Sometimes it's the only way to make web form validation do what you need it to. See this question for an example of extending/modifying validator behavior.
Since I'm new to asp.Net c#, I was wondering is someone can give me an
example or idea as how to achieve this?
Consider using ASP.Net MVC instead of web forms. The web forms model is old and "fights" you on tasks like this. If you are just starting out, I'd suggest at least investigating MVC and see if your time is better spent.
A lot of jquery plugins was created for this reason :
http://tinyurl.com/qetudk8
I believe if you add a
if(Page.IsValid) {
// Code here
}
around the button that is submitting the form, the page should fire off validation errors.
I decided to use the ASP.NET Validator to validate my dozens of inputs of my WebForm. It works fine on the Client side. I mean, i'm totally ok with validating the inputs without "Posting the Page back" etc.
But when i try to use the Validator on code behind, it gives me that Page.Isvalid attribute, and i get confused with its reliability. Here is the questions that i couldn't answer by myself:
Is Validator reliable enough to be used on client side? (Besides disabling javascript, can it be manipulated?)
How does this Validator reach the validity information on server side? (Is there a generated C# Validator code somewhere or does it take the info directly from the client-side?)
Here is the code that i wrote to validate my inputs also on server side:
foreach (IValidator iValidator in Page.Validators)
{
if (!iValidator.IsValid) { return false; }
}
But, is it independent from .aspx and .js? Can i rely on it on server side?
You should always validate also on serverside, this is mostly done automatically by calling Page.Validate.
From MSDN:
This method is invoked when a user clicks any ASP.NET server control
that has the CausesValidation property set to true, which is the
default. These include the Button, ImageButton, and LinkButton Web
server controls, the HtmlInputButton, HtmlInputImage, and HtmlButton
HTML server controls, and controls that can automatically post back to
the server such as the TextBox, CheckBox, ListControl, and
BulletedList controls.
If you want to force validation of a different ValidationGroup you can call it manually:
Page.Validate("MyValidationGroup");
If(Page.IsValid)
{
// ...
}
Note that you should check Page.IsValid only after you have called the Page.Validate method, or set the CausesValidation property to true in the OnServerClick event handler for an ASP.NET server control that initiated the form processing.
I've used jQuery dozens of times with PHP with great success. I'm working on an ASP.NET application and would like to use jQuery in the same manner.
Basically, I've got a masterpage that has the form and a webform that has all the form fields and data. A user can submit the form multiple ways - selection of a drop-down, button, etc. I want to catch all submits and use jQuery to submit the form. While the form is being processed, I want to display a new DIV with some text in it. Finally, I want to replace that div with the new form.
How can I accomplish this with the way that ASP.NET works?
Actually ASP.NET will post-back if you use its built-in JavaScript __doPostBack function. There's no other painless way for doing that.
That means you can use jQuery to handle drop-down lists, buttons or whatever (X)HTML element event and handler's body will invoke __doPostBack.
It's unclear that you want is a full-postback, but a partial one using AJAX.
If you're looking for a solution for sending form values to the server without a full-postback, I believe you've these options:
Callback API: http://msdn.microsoft.com/en-us/library/ms178208.aspx
Page methods, update panels: http://msdn.microsoft.com/en-us/magazine/cc163480.aspx
Anyway, let me give you an advise: ASP.NET works quite different compared to PHP and you'd not try to reproduce some known PHP solutions in ASP.NET. You need to change your mind.
About showing a DIV or anything while something is processed, play with initializeRequest ASP.NET AJAX PageRequestManager:
http://msdn.microsoft.com/en-us/library/bb397460.aspx
But that would depend on what AJAX API you're using, because since Microsoft AJAX will be replaced by jQuery in the next times, I'll need to say that you need to do that in some jQuery approach, like creating some $.ajax wrapper so your code will be able to listen when an asynchronous request is going to be made and you can perform actions by handling that situation like showing a DIV or any loading notice.
In ASP.NET Webforms formposts aren't as easy as they are in php. If you're new in ASP.NET development try http://www.asp.net/mvc. A common framework which allows you to implement TypedViews (ViewModes), simple request to modelbinding, and so on...
mh, sample:
[HttpPost]
public JsonResult Insert(string name, string vorname) // name&vorname filled by $_POST:)
{
var #new = new Person { Name = name, Vorname = vorname }
this.repo.Insert(#new);
return this.Json(new { success = true, newId = #new.Id });
}
If I have a textbox in my view:
<div><%= Html.TextBox("Comments", Model.Comments)%></div>
I want to post the contents of this textbox to the controller with an Ajax call. I only need this one value though, so I don't want to post the whole form back.
<%= Ajax.ActionLink("update", "UpdateComments",
new { comments = /* ????? */ },
new AjaxOptions { HttpMethod="POST" })%>
How do I get the textbox value?
Rather than writing server-side ajax code, you should use client-side Ajax (e.g. jQuery) to get the runtime value of the textbox and post that value.
using jQuery, you could retrieve the value in the following manner.
$("#Comments").val();
Ajax.ActionLink is a helper function, that generates a JS-enabled link, that sends data via AJAX. Because it is generated serverside, and the value is generated on the client side, you can not pass a single value like that. You either have to manually write HTML and JS, or submit a whole form containing this element (and watch out not to nest it inside another form).
You can use Ajax in jquery. Like this
function FunctionName() {
$.Post(URl, function(data) {
});
}
I have 10 defined textboxes with strings.
I have to check all if they are not empty while clicking ok button
whats the cleanest way to check them all and when function is at end. each checkbox which was empty to give this a specific CSSclass. perhaps. ClassError. ( which highlights red)
I'm happy for answers.
I would add RequiredFieldValidators to them, as well as a ValidationSummary control.
edit: You can also add fancy AJAX effects with the ValidatorCallout from the AJAX toolkit.
edit: Validator controls also support client-side validation.
Using javascript or C#?
Javascript I will create an array of textbox and loop through it.
C# just go FindControl within a Panel or the Container of the text box and go something like this
foreach(Control C in ContainerID.Controls)
{
if ( C is TextBox )
{
if ( String.IsNullOrEmpty((C as TextBox).Text))
{
// Do things this way
}
}
}
Something like this would work on the client side using jquery:
$('input').filter(function(){return this.value=="";}).css("CSSclass");
edit: I just saw the C# tag, I'll leave this here for posterity though.
What you're doing might be simple enough to do easily with some custom javascript code, though I would say that in general the built in validator controls are both easier to use and more robust than a simple validation routine that someone might write. In addition to client-side validation, the validator controls also perform server-side validation to ensure that the data submitted is truly valid, in case someone has javascript disabled in their browser.
If validator controls are included on the page, then they will include some javascript functions that you can invoke, such as Page_ClientValidate(). I believe this will return a boolean telling you whether validation passed and will trigger the visual indicators that identify what the errors are. You can execute Page_ClientValidate('') to trigger only a group of validator controls; actually I think you must do that in order to trigger validation on any validator controls that have a value in their ValidationGroup property, as I don't think Page_ClientValidate() will trigger their validation logic.
There is a CustomValidator control that you can point to your own client-side function if you want, in case you do have some special validation logic that you can only implement through a custom javascript function. This is nice to use, because then your custom javascript function will be executed by the built-in validator framework along with any other built-in validator controls that you might choose to include on the page.
Side note regarding client-side validation: I suggest that you avoid doing the following to trigger validation:
onclick="return myValidationFunction();"
because if there is any other javascript code being injected into the onclick event, your return statement will prevent it from executing. So instead, I suggest doing this:
onclick="if(!myValidationFunction()) return false;"
That's bitten me enough times that I thought I'd just throw that out there. This problem is particularly noticeable if you have an ASP.Net button on which you've set the UseSubmitBehavior property to false, as it will cause the button to render as an HTML "button" control instead of a "submit" control, and as a result, executing a return statement, either true or false, will prevent the button from triggering a postback.