ASP.NET Form validation - success event in JavaScript? - javascript

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.

Related

Compare duplicate values of two select in materializecss framework

I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime

trigger unobtrusive validation but prevent submit on mvc4 form

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.)

jQuery custom validation in asp.net mvc 3 razor view

I have very basic knowledge about JS/jQuery. I need to perform check on the value of certain text boxes. The example just recreates the problem I heave with the real application which is a lot bigger and the tables are dynamically created based on a data from a data base, so in run time I add the classes on which I base my jQuery logic.
Here is the jsfiddle example - http://jsfiddle.net/Xhnbm/
There are three different checks I need to do - for float, for string length and for float, however you may see that the validations is not performed I always get the integer exception and even if you remove the integer check the validation is not working either, so I guess the problem is not in the functions themselves but somewhere else.
Thanks for help.
P.S
It seem I can't submit the question without adding code. All the code is in the jsfiddle example but since I need to add some here too, I think that the problem is either in the way I declare may functions that perform the check or here :
$('#submitDocument').click(function () {
try {
if ($(".checkString16").val().length > 16) {
throw "The text can be up to 16 symbols";
} else if (!mathFunctions.isInt($(".checkULong").val())) {
throw "Insert integer";
} else if (!mathFunctions.isFloat($(".checkFloat").val())) {
throw "Insert float";
}
validationResult = true;
} catch (exc) {
alert(exc)
validationResult = false;
}
return validationResult;
});
in the way I try to execute the validation when the submit button is clicked. But being no Js programmer at all I don't want to point you to wrong directions.
$('#submitDocument').click(function () {
var validationResult = true;
if ($(".checkString16 input[type='text']:first").val().length > 16) {
validationResult=false;
} else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
validationResult=false;
} else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
validationResult=false;
}
return validationResult;
});
This should do the trick.
If the #submitDocument is a input type='submit' and you use it to submit the form, you should try this way:
$('#submitDocument').click(function (e) {
if ($(".checkString16 input[type='text']:first").val().length > 16) {
e.preventDefault();
} else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
e.preventDefault();
} else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
e.preventDefault();
}
});
The e.preventDefault() will prevent the submit button from doing it default handler, which is submitting the form.
You can always submit the form manually from the code, using $("#formId").submit();
PS. Make sure that you are also validating those values in code behind, because simple jquery validation is easy to come around.

jQuery with remote validation does not wait for answer from server

I've noticed, that sometimes my validation code works wrong:
var $validator = $("#checkoutForm").validate();
...
if (!$validator.element($sameShippingAddress)) {
...
}
Debugging with Firebug showed, that sometimes $validator.element($sameShippingAddress) would return undefined (I guess it just does not wait till response is returned) and that would be assumed as false, even if element is valid.
If add code like this before if statement, everything works fine:
while (validator.element($sameShippingAddress) !== undefined) {
}
Question is if that is right solution and there's no better way to handle problem with validation plugin itself?
Update: I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Infinite while loop on validator variable is not a good choice. Instead use the code below that utilise Javascript timer. You can show animated processing/server response graphics after validate() method.
var validator = $('#resetpassword').validate({///your code...})
doTimer();
function timedCount()
{
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (validator === undefined)
{
timedCount();
}
}
if(validator==true)
$('#form').ajaxSubmit(options);
It's hard to tell how you are handling successful submissions or if you uses the css class to denoted required fields, but the following is how it's done in the demo for the plugin:
$.validator.setDefaults({
// code to be executed on submit
submitHandler: function() { alert("submitted, replace this with your server request");}
});
$().ready(function() {
// validate the comment form when it is submitted
// use css class .required for fields you want the validator to check
// if your form is valid then it is handled by the submitHandler
// if not the plugin displays error messages
$("#checkoutForm").validate();
//validate can take a block for custom validation and error messages
});
Hope this helps you find a solution and isn't just more of the same (also just realized this question is a year old, but I already wrote this so...)
Obiously, it is not the best solution. Instead add
if (!$validator.element($sameShippingAddress)) {
...
}
in the Ajax callback function.

asp.net validation with validation group calling Page_ClientValidate not working as expected

Hi I am calling the following javascript when user clicks complete button which is to call validation on all of the validation groups which i have 3.
but what is happening is that only the validation summary for the Photos one is being displayed when the others should also be showing. Can anyone help?
function EnsureValidation() {
Page_ClientValidate('PropertyInformation');
Page_ClientValidate('MarketCondition');
Page_ClientValidate('Photos');
}
See Page_ClientValidate() with multiple ValidationGroups - how to show multiple summaries simultaneously?
Edit
Can't you just call Page_ClientValidate() (without any arguments) to validate all controls on the page?
I know this is an old post, The issue with using only Page_ClientValidate() is that, if you want to validate one group at a time, it won't work as it fires all the validation groups, you can do something like this,
function something(){
if(Page_ClientValidate('Save'))
{
//Your Code
}
else if (Page_ClientValidate('Group2'))
{
//your code
}
else
{
//your code
}
};

Categories