Enable ASP.Net validator without immediately running validation - javascript

Question
Can I enable an ASP.Net validator without running validation immediately (i.e. giving the user a chance to input values before running it, but still force running validation on form submit)?
Background
I have a form that allows a person to input their family data when they check in their child(ren) into a public daycare system. We have five fields that I need to force parents to actively consider (allergies, special needs, etc). The values are not actually required, so too many parents were just skipping over the fields when their children should have had values specified.
My solution is to have a required field validator that's disabled if they click an N/A checkbox next to the textbox. (If someone has a better solution, I'm all ears; the UI of this form--which I inherited--makes me want to gouge out my eyes.)
The other thing is that when the "Add Family" button is clicked, four empty rows are auto-generated: two adults and two children. Whether a row represents a child or an adult is determined by a drop-down in that row. If "adult" is selected, or if the first name textbox in that row is empty, the validators are disabled.
The validators of all five fields are enabled as soon as both the drop-down selected value is "child" AND the first name textbox is not empty. The issue is that running ValidatorEnable() causes the form to validate. In the common case, the fields will be empty, since first name and "family role" (adult/child) will be inputted before whether that person has allergies or are potty trained. This means as soon as they input the name into a row specified as child, ASP.Net's all like "HEY, DUMMY, YOU HAVE AN INVALID FIELD!!!1!".
So, I would like to enable the validator, but prevent validation until the user actually either inputs an empty value into the allergy textbox, or they try to submit the form.
Is this possible?
Note, I would use a custom field validator, but validation isn't run on empty fields; afaik, only required field validators do that.

I've just adapted the answer here: http://veskokolev.blogspot.co.uk/2007/11/how-to-disable-validation-group-with.html to enable some validators client-side with jQuery. Once they were enabled, the validation function did run - I don't know how to stop it (without modifying the ASP.NET JS code, which I guess is an option?); so I simply hid the messages until the validation is run again (which is easy enough with $(x).hide()).
Considering all the client-side code does is show the warning and stop you submitting I think this is OK. The usual things that will cause the validator to re-run will re-show the message.
So if I have validators like:
<asp:Validator runat="server" CssClass="js-validator-set-a" />
I can use this Javascript:
toggleValidators('.js-validator-set-a', true);
function toggleValidators(selector, enable) {
// get the page validators into a jQuery object
var vals = getJqueryObjectFromArrayOfEls(Page_Validators)
vals.filter(selector).each(function (i, o) {
ValidatorEnable(o, enable);
$(o).hide();
});
};
function getJqueryObjectFromArrayOfEls(elsArray) {
var x = $();
$.each(Page_Validators, function (i, o) {
x = x.add($(o));
});
return x;
}

I just came across a similar requirement. WhatI did was first to set a valid value to the compnent to be validated, then enable the validator and finally I cleared the value in the component again. Something like
$('#<%= tbxValue.ClientID %>').val('X'); // set a value to the textbox
ValidatorEnable(<%= rfvValue.ClientID %>, true); // enable the required field validator
$('#<%= tbxValue.ClientID %>').val(''); // clear the value from the textbox

Yes, it's possible in a variety of ways. The two most common and perhaps sensible things to do are :
Have validation occur completely in the code-behind via code only
Have ASP.NET validators that are set to enabled=false and then turn them on and call Page.Validate()

Instead of using that function, you can make your own function that has some of the same code as ValidatorEnable, but wont trigger the validation.
function myValidatorEnable(val, enable) {
val.enabled = (enable != false);
}

Related

disabled.bind in Aurelia not working correctly

I have a form, in the form there is a custom component that has certain fields in it. At the end of the form there is a button. The button has...
disabled.bind="!(formValid && subFromValid)"
Now, on the custom component I have a two-way binding of a variable "subFormValid" The subFormValid is only valid when the validation in the custom component is valid. So, the sub form validates some fields and sets subFormValid = true. Even though the "formValid" is false, the button is now enabled.
I can't figure out why and it is driving me nuts. I even went so far as to add a get function to a variable and add console logs in it, like so...
<button type="submit" disabled.bind="wholeFormValid">Submit</button>
Then in my class I have...
get wholeFormValid() {
console.log("validating form");
console.log(!(this.formValid && this.subFormValid));
return !(formValid && subFormValid);
}
I get a million plus lines in the console, but I was able to watch it, the entire time. When I first load the page it was logging...
validating form
true
Then I filled out the subform, and checked the console. The console showed...
validating form
true
Yet, the button was now enabled.
For some reason whenever subFormValid = true, the button is enabled, regardless of formValid.
Does anyone know how to disable a button unless 2 conditions are met? Everything I do enables the button as soon as subFormValid is true, even though the console is still logging "true", which should disable the button.
Just to help out, if anyone is wondering why there is a subform in the form it is because the address needs to be validated using Smarty Streets and we want to be able to reuse that part of the form in other places, so I created a custom component for the address section that validates the input, and validates the address. It is being called in the form like so...
<require from="components/smarty-streets"></require>
Then using like this...
<smarty-streets form-is-validated.two-way="subFormValid"></smarty-streets>
Then in smarty streets I have...
#bindable formIsValidated;
and I change the value from true to false and vice-versa depending on the validation in the component.
I have tried to recreate your problem using the following:
<input type="checkbox" checked.bind="formValid"/>
<input type="checkbox" checked.bind="subFormValid"/>
<button disabled.bind="wholeFormValid">Submit</button>
I noticed in your function that you used this.formValid in the console.log line, but in the return line you used formValid, without this. This seems to be a different variable than your actual binding variables. I think your function should look like this:
get wholeFormValid() {
console.log("validating form");
console.log(!(this.formValid && this.subFormValid));
return !(this.formValid && this.subFormValid);
}
Edit: I also strongly recommend using the #computedFrom decorator on your get() to reduce the amount of calculations aurelia does. You can read more on that here.

Javascript Disabling Multiple field objects onchange

I was using the following script to disable multiple field objects when one field was selected, I have changed the fields so that they no longer have a default value of zero but can have varying values:
JS
function disablefield(fieldObj)
{
var fields = new Array('Seat_1200', 'Seat_1230', 'Seat_100','Seat_130','Seat_500','Seat_530','Seat_600','Seat_630','Seat_700','Seat_730','Seat_800','Seat_830');
for(var i=0; i<fields.length; i++)
{
fieldObj.form[fields[i]].disabled = (fieldObj.value!=0 && fieldObj.name!=fields[i]);
}
return;
}
Can anyone suggest a way to detect the current value of the fields seat_xxxx (which are loaded dynamically) integrate it into the above script then disable the all fields when the value one changes. Or alternatively if the field is de-selected i.e. the user changes his mind and selects another option, then the field is set to zero automatically to satisfy the above script re-enabling all the selection options.
In response to the problem from the author I have a new code set.
I would use a Jquery button set to represent all the tables you have. Then selectively disable them based on the result. Below is a fiddle
http://jsfiddle.net/05cpss80/
Buttonsets are really just classed checkboxes but they give you what you need.
<input type="checkbox" id="check1"><label for="check1">Table1</label>
As such you can add additional classes to them to stop them from "checking"
$('#check2').attr("disabled", "disabled");
I would recommend you add some css to make it more obvious, but try the fiddle. Click 2, then the button and it will no longer work. (Thus when they make a selection you call disable on whatever tables you need)

Jquery validation engine ajax, two fields same function?

The jQuery validation engine plugin has the ability to do ajax validation; which works gret except for one small catch...
It sends off the field ID instead of the field name to be validated.
Why is this an issue?
I have a simple item that to create it only requires one textbox to be filled out; so we have this as a modal on every page for managing said item.
We use the jQuery validation engine plugin to validate that the entered value is unique.
Now this also means that the modal shows up on the edit page. Which obviously has the title in a field as well for you to edit.
And we want this field to be validated as well but because the validation engine sends across the field ID instead of the field name we must give the two fields different ID's
e.g. createtitle and edittitle and then on the backend have
if($fieldId == 'createtitle' || $fieldId == 'edittitle'){$fieldId = $fieldId}
Which really is an ugly approach; is there any way to get it to use the name; or another attribute instead?
Maybe this plugin could help you. It uses class names of your element to validate.

Javascript form validation, how do I enable a button and check details (more details inside)

Ok here is how my validation works
There are three text boxes. name | email | message.
Onchange of each of them runs a function that validates them and adds 1 to a counter.
functions are: email(), name(), message().
I have another function called CheckBut, which checks to see whether each of the text boxes has been validated by making sure the counter ===3. it then enables the send button.
WITHIN each function email, message, name i have {counter++, CheckBut()}
HERES THE PROBLEM: A user will enter the name right, and then click on the email field. This will then run the validation code for the name. They then enter the email and click on the message field, and this runs the validation code for the email field.
When they enter the message they cant click on the button becuase its disabled AND the function to validate the messgage field WONT run until they click somewhere else. HOW can I solve this? I was thinking of BLUR() but I dont know how to run make it work within the confines of my form.
I suggest you attach your listeners to onKeyUp instead of onChange. This will get them to run before the user clicks out of the text fields, which ensures that the send button will be enabled before the user tries to click it.
However, by listening to onKeyUp your validation functions will be executed many times and your counter will probably grow larger than 3 before the user even leaves the name field. To address this, I suggest you remove the counter variable and instead track the validity of each value using three separate boolean variables (e.g, isNameValid, isEmailValid, isMessageValid). Each validation function would simply assign a true or false to its respective variable. CheckBut() would then be changed to simply check that all three variables are true.
You may use onkeypress event for check field changes, and setTimeout for run validation if field not changed in last 3-5 seconds. Looks like this.
<script>
var validNameTimer = null;
function nameValidWait() {
if (validNameTimer != null) {
clearTimeout(validNameTimer);
}
validNameTimer = setTimeout(nameValid, 4000);
}
</script>
<input id="name" onkeypress="nameValidWait()" />
Fix
Replace onchage to onkeypress
You probably should not disable the button. Instead, run all 3 validations on button click event and if validation fail display an error message (optionally) and stop the execution (return). Error message can be shown in HTML element, or you can use alert(msg) function. Hope this will help. Best rgds, AB

Javascript: fast way to check if form contents have been changed before submission

Simple question (I guess)...
I'm in an "edit-some-element" html form.
As the page load, the form is filled with current element attributes (eg. name, etc.)
I could modify some input fields or even decide not to do that but I click the same on submit button because is the only available one.
MY QUESTION:
is there a property/attribute of the input elements containig the initial input values that I can access to compare them with the current ones when I click on submit button?
In other words:
is there a fast way to check if at least one input field has been changed before submitting the form? (so to stop the event if an update isn't really necessary)
(and I mean "really changed" not considering as changes when I modify something but rewrite it as it was before)
I'd like a minimal example:
How to check if a simple input-text "name" has been changed
P.S.
Of course, to trigger the "check-if-something-changed" function,
if I decide to use pure javascript I would use onSubmit event while using jQuery I would use something like:
$('#formMod').submit(function(){ ...
Thanks.
You can use the input element defaultValue dom property:
function validateInput(input) {
if (input.value == input.defaultValue) {
alert("Please change field.");
return false;
}
return true;
}

Categories