Using jQuery Validation plugin for a div instead of form? - c#

NOTE: I referred these questions Qn1 , Qn2 before asking this . But honestly the answers are not working. Please suggest a solution..
I am doing validation to my input fields using jquery validation plugin. My code works fine when all the tags are kept inside a form tag and accessing it in jquery like, $("#formID").validate() --> this is working fine... But I want to achieve the same for a div instead of a form.
I tried it like this: $("#divID").validate() but it's not working...
Below is my code. please take a look and tell me how to achieve it for a div.
<script type="text/javascript">
$(document).ready(function () {
$("#content").validate({
onfocusout: true,
rules: {
fullname:
{
lettersonly: true,
required: true
},
age:
{
required: true,
number: true,
min: 20,
max:98,
nowhitespace:true
}
},
messages: {
fullname: "Please specify your name.",
age:"Please enter your correct age."
}
});
});
</script>
<div id="content">
<p>
<label for="fullname">Full name:</label>
<input type="text" name="fullname" id="fullname" /><br />
<label for="age">Age</label>
<input type="text" name="age" />
</p>
<p>
<button id="submit" value="">Search User</button>
</p>
</div>

Quote OP: "NOTE: I referred these questions Qn1 , Qn2 before asking this . But honestly the answers are not working."
Incorrect, the the accepted answer on Qn2 is working perfectly:
The validation plugin is (currently) designed to work on a <form>,
and only on a <form>. You can also note that all of the plugin
documentation references a form, not any other generic container.
You must use a form element with the jQuery Validate plugin. There is no workaround for this.
However, if you just want to validate some inputs without actually submitting a form, there are lots of working solutions. Example: http://jsfiddle.net/GmQ5d/
Full Documentation

Unfortunately, not the answer you want to hear, but using the JQuery Validate plugin you can't perform the validation on anything other than a form tag. You may note that all of the plugin documentation references a form and not any other generic container, e.g Div.
This website shows you how to implement JQuery Validate with webforms, not as easy as the normal examples that you get from JQuery, but still good.

jQuery's own validation only works for forms. This plugin, however, looks like it should work without forms. According to their documentation that is, I haven't tested it myself.

Very outdated, but seems like it still requires one possible solution to be added. If you cannot use form (in .NET it simply cannot be more than 1 form per page), you can still validate directly each field.
So instead of
$("#divID").validate();
you can use:
var isValid = $("#fullname").validate();
isValid = $("#age").validate();
if(isValid){
// do submit form
}

Related

How do I do some custom unobtrusive validation in mvc in code?

Trying to get my head around unobtrusive validation. I created a simple page like this:
#using (Html.BeginForm())
{
<text>Validation for name should fail unless this box contains the word christmas</text>
#Html.TextBoxFor(c => c.IsChristmas, new { id = "IsChristmas" }) <br />
#Html.TextBoxFor(c => c.Name)
#Html.ValidationMessageFor(c => c.Name)
<br />
<input type="submit" value="Submit" />
}
The model just has two strings, [Required] Name and IsChristmas.
This works fine, if you press submit when the text box is empty, you get the Name is required validation error appearing.
What I want to do now is make a validation error appear when they try to submit, if the first textbox doesn't contain the word 'Christmas'. This is just to learn how I can create my own custom validation types. I don't want to use data attributes, I want to do it entirely in javascript. I'd like to hook into the existing unobtrusive stuff if possible.
Any ideas?
I figured I could write a function first:
function isChristmas()
{
return $('#isChristmas').val() == 'christmas';
}
Then perhaps I can register it somehow so it is called on submit? Either directly into the validation code, by registering some kind of handler, or write my own handler (a submit button click event) that calls isChristmas() and if it's false, calls a method to display the validation error.
I am not sure how flexible the unobtrusive stuff is. I guess another desirable thing would be that if the page is submitted with the validation being bypassed, I can check server-side as well and have it go back to the view and somehow display the error that way too.

Open a new window with Same session using jquery/C# Razor

I am trying to open a new window with same session as the current one. I wrote some code below but its no luck yet.
For example lets say i have a form with a label (Name), textbox (where the text goes in)
and a button when pressed takes me to a new window.
If i press the button it should open a new window with the same form elements and text in the textbox if it was put in before.
Also please note the new window must be opened as a new tab in the browser with the same state and same elements as in the previous browsers.
Anyone got an idea on this (using razor view engine or jquery/javascript) ? Thanks in advance.
<label for="Name">Name</label>
<input type="textbox" value="nothing" id="text" />
<input type="button" value="press me" id="submitButton" />
$(document).ready(function()
{
$('#submitButton').click(function()
{
var currentUrl=document.URL;
window.open(currentUrl,"newWindow",300);
event.preventDefault();
});
});
You may be able to accomplish this by using modals instead of popup windows. Jquery UI has built in modal support: http://jqueryui.com/dialog/
The advantage to this approach is that no data needs to be passed into a separate page. Your modal code would look something like this, with jQuery Dialog. This would go on the same page as your initial inputs:
<div id="dialog" title="Basic dialog">
<input type="text" id="popupText" name="popupText" />
</div>
and your click event would modified update the modal input and show the modal:
$(document).ready(function(event)
{
$('#submitButton').click(function()
{
$("#popupText").val($("#text").val());
$("#dialog").dialog();
event.preventDefault();
});
});
This could definitely be cleaned up but I believe it'll do what you need pretty simply. The dialog can contain any html elements, so you can add a separate form if necessary.

How to disable a link tag to open fancybox mentioned in href url?

In a ASP.NET Web Application, facnybox of jQuery is used on button click.
As mentioned in link: http://fancybox.net/howto
<a id="lnkEmail" href="../Email/Default.aspx" runat="server">
<div id="DivBtnEmail" class="button" runat="server">
<asp:ImageButton ID="BtnEmail" ToolTip="Send Email" CssClass="image" ImageUrl="../img/tlb_list_email.gif" OnClick="BtnEmail_Click" runat="server" />
</div>
</a>
In some cases during application, there is a need to disable the buttons which opens fancybox.
I used asp:button property to disable the button.
BtnEmail.Enabled= false;
But, due to link tag it still works and open the url mention in link href in a fancybox.
How to disable a link tag to open a fancybox ?
I've tried the solution mention in link : how to disable link in jquery
But, it didn't work for me.
Any help ???
Try this:
$('#<%= BtnEmail.ClientID %>').prop('disabled', true);
You can call a return false; That way, JS doesnt return the event handler.
$('#lnkEmail').click(function() {
if (conditions) return false;
// else do your stuff
});
You should use some kind of selector for fancy box that allows you to be more flexible.
If you’re selecting html elements where fancybox will be applied using class then you can create another identical class but named differently and then use that.
This doesn’t require additional javascript but it will require additional CSS definitions.
Above discussion helps me to figure it out how to disable the link tag. I disable the link tag from server side where I was enabling/disabling the other buttons w.r.t conditions.
It was the "Disabled" property which needs to be updated accordingly.
this.lnkEmail.Disabled = true;

adding conditional requiredFieldValidators to dynamically created form in c# asp.net

Ok,
i have a fully rendered dynamic form ( i do not know the content of the form, it is provided to my via a webservice )
i used asp.net RequiredFieldValidator for validation, because i read in this article that we could dynamically switch validators on and off depending if the field is visible or not
with the ValidatorEnable(val, enabled) function.
though now that i got the form rendered, i'm running into a bit of trouble with this javascript, as i don't want to put it in the aspx file itself, (don't have a control there anyway since the form is build up in codebehind from the webservice data...)
so i took a look at the clientId and it turns out the validator's client ID is the id of the span it renders to.
so i tried running this in firebug to test if i could enable / disable one of those validators, but that seems not to be possible, a jQuery span element does not have a property to enable it.
ValidatorEnable($("#ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_reqAnswer_373ac8b7_8da9_467b_b9b4_d586e45a7504"), false);
and the html that goes with this
<div class="question-container question-odd" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_question-373ac8b7-8da9-467b-b9b4-d586e45a7504">
<div class="question-meta">
<h3 class="validation-label">Which club have you visited?</h3>
<span style="display: block; margin-bottom: 10px; margin-top: 5px;" class="error validation" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_reqAnswer_373ac8b7_8da9_467b_b9b4_d586e45a7504">Please fill out this field.</span>
</div>
<input type="text" class="answer-container text" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_answer_373ac8b7_8da9_467b_b9b4_d586e45a7504" name="ctl00$ctl00$ctl00$ContentPlaceHolderDefault$MasterWithNavContent$Poll_4$answer_373ac8b7_8da9_467b_b9b4_d586e45a7504">
</div>
Does someone know where i'm going wrong here?
maybe I'm to quick to jump from the serverside ClientId to the <span> which the RFV renders into? but they seem exactly the same.
hope someone can point me in the good direction!
Maybe a better approach would be to loop through the client-side array of validators (Page_Validators) and find the validator which you want to disable.
See also this MSDN page and this codeproject article for more information.
Perhaps a more appropriate way to do this would be
ValidatorEnable($("<%= reqAnswer.ClientID %>")[0], false);
Using <%= reqAnswer.ClientID %> avoids having to guess at or hard-code the client-side ID of the validator. Adding [0] after the jQuery $() gets the actual validator DOM element instead of the jQuery wrapper.
Source for [0]

MVC 2.0:How to send simple TextBox value to Action with an ActionLink?

Basically, i don't want to use <input type="submit"> mainly because it's a button, i'd rather user ActionLink, so i am using Ajax.ActionLink, and i'm not sure what to place in the routeValues argument for it to pickup the new (edited) data (user enters comments etc) and send it to my action. would any of you know? thanks.
this is what i have, but of course, it sends the original comment before user edit back to the server/action :)
<%= Ajax.ActionLink("Update", "UpdateComment", Model.Comment,
New AjaxOptions With
{.UpdateTargetId = Model.CommentDivId, .HttpMethod = "Post"})%>
ps: i know how to do this in javascript, and doing ajax posts etc, hope to find and mvc only solution
Basically, you can not do this alone in an ActionLink and MVC, you need to use JavaScript to achieve what you are after! If you want to use JavaScript, there are examples above you can choose from!
I do wish therewas a HTML helper so we didn't need to do messy jquery mashups to access real-time form data, but there isn't, perhaps someone can create a helper and share it with us?
I would recommend you still wrap the comment field with form and submit the fields with an anchor and some javascript.The generated html looks like...
<form id="the_form">
<textarea id="comment"></textarea>
submit
</form>
You can easily replace this with the HtmlHelper in MVC or some other ViewEngine code, but the point is to submit the form with the link (anchor tag) and the parameters will get mapped to the action method.
Hope that helps,
Eddy
PS. You could also use the Ajax.BeginForm to achieve the same.
If it's only the button you're worried about then why not apply a bit of css to change the button into a link? No one will know the diff and you'll save yourself a bit of work.
If this is not what you're after then let me know and I can remove this answer.
As for Ajax, I'm not sure you're model will be updated as it should be out of scope. I think the way to do this is to pass all your data across as variables. Not an ideal solution really.
I'd use the css approach on this one.
edit
<head>
<style>
.buttonAsLink{ background-color:white; border:0; color:Blue; text-decoration:underline;}
.buttonAsLink:hover{ text-decoration:none;}
</style>
</head>
<body>
<input class="buttonAsLink" type=submit value="Click Me" />
</body>
How about just making an ajax call with jQuery on click of your html link? Something like this or this.

Categories

Resources