I have a function called generate_form which uses jQuery to create a form and insert it into the page. Several other functions call this general one to create their form, and it in turn returns the form.
In order to do validation, i want the caller to be able to provide their own validation function as the specific use case has non-standard constraints (such as having to issue ajax calls to check/verify things). The issue i'm running into, is i'm not sure how to get the custom validation function into the submit event of the form.
Very simplified and truncated code:
function user_test() {
$('#formcontainer').append(generate_form(
{
name:'test',
id:'user_test_form',
fields:
[
{name:'username',type:'text',id:'username'}
],
validation:function() { return $('#username').length > 0; }
})
);
}
function generate_form(data) {
var form=$('<form>',{id:data['id']});
//SNIP: add fields to form
$(form).submit(function(event) {
event.preventDefault();
//does not work, because data is undefined in this scope
if ( !data['validation']() ) {
//SNIP: validation failed notice
return false;
}
//SNIP: post form
});
return form;
}
Several ways around this. One would be to bind the submission callback to the context of data, so:
$(form).on('submit', function(event) {
event.preventDefault();
if (this.validation && !this.validation()) return false;
}.bind(data));
Another would be to pass data as event data. This is done via the third param of .on():
$(form).on('submit', null, data, function(event) {//...
The original data is then accessible in the callback via event.data.
Also bear in mind you were assuming a validation callback was passed before calling it which, if there isn't one, will error.
Related
I have a form in my jsp wherein I enter a value. This is then inserted into a table on my database. However, I would like to ask the user first to confirm his submission. I used this:
function askConfirmation() {
var confirmSubmission = confirm("Do you wish to add this entry?");
if(confirmSubmission) {
return true;
} else {
return false;
}
}
Although this does the task of suspending submission, it's not quite what I had in mind. I tried using a modal but I don't know how to get the values I used from my EL and place it in the modal after the button click. How do I do this?
I am not quite sure how you have your form inputs setup, but you can pass an object representing all your form inputs as an argument into askConfirmation() function and then pass that to confirm(). This will display to the user all the information in the form. Eg.
function askConfirmation(formInput) {
var confirmSubmission = confirm(formInput);
if(confirmSubmission) {
return true;
} else {
return false;
}
}
So in this way, you can access members/fields in the object and format them accordingly. You can also use jquery dialog() function to achieve this if you don't like the lnf of the window. The bottomline is, just pass the object that represents your inputs value into whatever that is used in displaying to the user for further confirmation. Hope this helps!
As Felipe T mentioned your values are already rendered you just need to get them with javascript here's an example using bootstrap modal https://jsfiddle.net/tf021so9/6/
-
However, I prefer using a confirmation dialog plugin in such cases like this one :https://myclabs.github.io/jquery.confirm/
-
UPDATE
Added this error, just says "Error caught"
<script type="text/javascript">
window.onerror = function() {
alert("Error caught");
};
xxx();
</script>
This is not working, I don't understand why.
My php script inserts data properly if called by itself without an if{method=post} statement
I tried with and without an if method = post argument on the php side to get the ajax below to work but I can't tell if the script is being called at all.
My aim is to submit the data without the user knowing, it's a coordinate / dimension update for a variable design interface.
This is my ajax insert which is supposed to work when a function is invoked after the stop is triggered eg. after an object is done moving which the function is invoked properly as I have set up sequential alerts to pop up after certain lines.
$("#form").submit(function(event){
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, {
id: $('#id').val(),
name: $('#name').val(),
wname: $('#wname').val(),
xcor: $('#xcor').val(xcor),
ycor: $('#ycor').val(ycor),
xwid: $('#xwid').val(xwid),
yhei: $('#yhei').val(yhei),
photo: $('#photo').val(),
targeturl: $('#targeturl').val()
});
posting.done(function( data ){
alert('success');
});
});
This is wrong
xcor: $('#xcor').val(xcor),
ycor: $('#ycor').val(ycor),
xwid: $('#xwid').val(xwid),
yhei: $('#yhei').val(yhei),
Those object are holding jQuery objects, not a value.
Looks like you want to set the value and use the new value. This makes me cringe, but it would do the job
xcor: $('#xcor').val(xcor).val(),
ycor: $('#ycor').val(ycor).val(),
xwid: $('#xwid').val(xwid).val(),
yhei: $('#yhei').val(yhei).val(),
You would be better off updating them before the call and just using the variable when setting the object. Or just use jQuery serialize() and don't deal with grabbing the elements.
i have a multi-page form that i am trying to validate using jquery validate. the user has essentially 4 options: next, prev, save, submit.
save, next, and prev all save the current page to the form as a whole; submit is the same as save, but fires some additional workflow-related functions then heads off to another part of the site.
i need to validate the user input at all times. the jquery validate is working great. but... i need to have some fields set as required. because the form is saved at each step, the input needs to always be valid, but i don't need the required validation until the very end (on submit).
the form is building a dynamic list of validations specific to the page it is on, like:
$(document).ready(function() {
$("#ctl01").validate({ onsubmit: false });
$("#_Qn_0e868ebe").rules("add", { maxlength: 200 });
$("#_Qn_d69e75a4").rules("add", { number: true });
$("#_Qn_adffbdec").rules("add", { maxlength: 200 });
$("#_Qn_adffbdec").rules("add", { digits: true });
});
so now, for required fields, i've added a .isrequired class to them, and i've decoupled the <asp:linkbutton>s to fire this client script:
function FormIsValid(sender, ishardsubmit) {
var form = $("#ctl01");
form.validate();
if (form.valid()) {
//if (ishardsubmit) {
// if (!IsRequiredValid()) { return false; }
//}
__doPostBack(sender, '');
}
return;
}
this part (the input validation part) is working great so far. the part i commented out is the part that is working not so great. it fires this function, in which i was trying to dynamically add required validators and re-evaluate the form. i can see it hit the .each loop for each of my required fields, but it doesn't seem to be working since it passes true back, even when required fields are empty.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function (i, item) {
$(item).rules("add", { required: true });
});
form.validate();
return form.valid();
}
i toyed with the idea of dropping the .net required field validators in to do this part, but i want to, if possible, stick with a single solution. especially since this feels so close to working.
thoughts? help? thanks!
Your jQuery .each() method is constructed improperly.
You want to target the whole object in your iteration, not key/value pairs. So remove i, item from the function arguments and use $(this) as the target selector.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function() {
$(this).rules("add", { required: true });
});
// form.validate(); // remove this line -> 100% superfluous
return form.valid();
}
Regarding your form.validate() line in both functions: You cannot call .validate() more than once on the page. It's only meant to be called once to initialize the plugin on your form.
Calling it subsequent times will have no effect. Otherwise, we wouldn't need to use the .rules() method as we would simply call .validate() any time we need to change rules. However, this is definitely not the case.
Add a class to your required fields called something like: "SubmitRequired"
Implement two functions as follows:
function SaveClick(){
//ignore SubmitRequired on save (and any disabled fields)
$("form").validate({ ignore: ".SubmitRequired, [disabled]" });
if $("form").valid()
{
do something;
}
}
function SubmitClick(){
//ignore only disabled fields (if any))
$("form").validate({ ignore: "[disabled]" });
if $("form").valid()
{
do something;
}
}
I have a form, this form has some values that are required, so in my viewmodel I have some things like:
[Required(ErrorMessageResourceType = typeof(Res_Errors), ErrorMessageResourceName = "errorPacienteNoSeleccionado")]
public int? scheduledIdPersonaSeleccionada { get; set; }
as well as a submit button, but I don't want to submit the form to the server, I only need to execute a jquery function if my validation passes.
The validation is working but I don't know how to prevent the form from posting and instead call my function.
if you only want to execute javascript on form submit (and not actually send the information) have a look at #Ajax.BeginForm:
#using (Ajax.BeginForm(new AjaxOptions { OnBegin = "MyFunction" }))
{
#Html.EditorFor(x => x.scheduledIdPersonaSeleccionado)
<input type="submit" value="Presentar" />
}
Alternatively you can hook in to the submit event and do it yourself:
$('form').submit(function(){
if ($(this).valid()) { // validation passed
// cal your jquery function here
}
});
Change your submit button to button type. Validation will call, but submit won't
<form>
#Html.EditorFor(x => x.scheduledIdPersonaSeleccionado)
#Html.ValidationMessageFor(x=>x.scheduledIdPersonaSeleccionado)
<input type="button" value="Presentar" onclick="DoSomething();" />
</form>
I solved it by hacking through jQuery Validate default options. jQuery Validate is used under the hood by unobtrusive validation.
If you have only one form to validate on the page, you can define globally a submit handler which will execute only when a valid form is submitted:
$.validator.setDefaults({
submitHandler: function (form, e) {
// your code
}
});
It has to be defined before the unobtrusive initialization, which occurs on ready. Or you will have to re-parse the form with $.validator.unobtrusive.parse(selectorOfYourForm).
In my case, having many forms with different needs, I have used something like this:
let submitHandlers = [];
$.validator.setDefaults({
submitHandler: function (form, e) {
let result = true;
$.each(submitHandlers, function (i, submitHandler) {
result = submitHandler(form, e) && result;
});
return result;
}
});
function addUnobstrusiveValidationSubmitHandler(submitHandler) {
if (typeof submitHandler !== 'function') {
throw 'submitHandler must be a function';
}
submitHandlers.push(submitHandler);
}
I leave to each submitHandler the responsibility of working only on forms it has to handle. The submit handler should check the form, and just return true; without doing anything else if it is not a form it should handle. So adding a bad submitHandler acting on unexpected forms will mess other forms or the whole page.
It would be better if we could define the submitHandler in the parse call instead, but currently this call does not take an options object.
(There is also some options which can be defined globally by assigning an object to $validator.unobtrusive.options, but I do not find much documentation about this beyond errorClass and errorElement options, and it does not seem to have an option for specifying a submitHandler. As far as I can see from the source, we could only define the following additional options, matching the jQuery validate ones: errorPlacement, invalidHandler and success.)
I would like to subscribe to whatever event is fired when my ASP.NET form is validated successfully.
Here is the scenario: On the click of a button on a payment form, I want to show a message 'processing,' however I only want to show this button when the for is validated succesfully.
I am using native ASP.NET form validation.
In a round-about way, you can if you override the Page_ClientValidate method as in:
var fn = Page_ClientValidate;
Page_ClientValidate = function(..) {
var result = fn(..);
if (result == true) {
//run code for success
}
}
I don't know why this was demoted but this approach is great because it works from all validation scenarios for customization (from buttons, WebForms_DoPostBackWithOptions client method, etc.).
HTH.
I don't think that the built in validators expose any such events. You could always use the CustomValidator and provide a OnClientValidate method that will combine the validation you're looking for as well as the UI changes you desire.
Call the following Javascript function whenever you want and pass the validation group name of your form to it..
function ValidateForm(ValidationGroupName)
{
var validated=Page_ClientValidate(ValidationGroupName);
if(validated)
{
//do the logic here
return true;
}
else
{
return false;
}
}
Hope this will help you....
I don't think it's going to be easy to do it your way but what you can do is the following:
<asp:Button onclientclick="if (Page_IsValid) return true; else {alert('Not Valid'); return false;}"/>
This will basically throw an error is validation is incorrect, otherwise it will continue.