Showing posts with label validation. Show all posts
Showing posts with label validation. Show all posts

Tuesday, November 30, 2010

validating dynamically created radiobuttonlists

I recently was working on writing a client validation function to go hand in hand with my customvalidator. My form had some regular ASP controls on it, and it also had a section of questions inside a repeater, since this section was designed to ask you to rate instructors, and the name and quantity of said instructors depended on which class it was. I don't remember trying to write javascript to check radiobuttonlists inside a repeater before but eventually read a helpful snippet here.

In the example at that link, the entire form is iterated through. In my case however the form had radipbuttonlists both in and out of the repeated, and I only wanted to iterate through the repeater for this check. I already had simpler functions for the rest of them. Additionally I did not want a message to pop up for every unanswered radiobuttonlist in this section, but merely one generic "please rate all instructors" message. So I wrapped the repeater in a div, and it is this div that the variable called container below references.


// Grabs all inputs - radio, checkbox, text, buttons and lists -sticks them in an array
var last = "NameUnlikelyToBeUsedAsAnElementName";

var container = document.getElementById("divRpt");
var allInputs = container.getElementsByTagName("input");

// walk through the array
for (i = 0; i< allInputs.length; i++)
{
var input = allInputs[i];
if (input.name == last) continue; // if this object name is the same as the last checked radio, go to next iteration

// checks to see if any one of similarly named radiobuttons is checked
else if (input.type == "radio" )
{
last = input.name;
var radios = document.getElementsByName(input.name);
var radioSelected=false;

//iterate over question options
for (j=0; j < radios.length; j++)
{
if(radios[j].checked)
{
radioSelected=true;
break; // Found it, proceed to next question
}
}
if (!radioSelected) // no option selected
{
bOK = false;
}
}
if (!bOK){alert("Please rate the overall teaching effectiveness for your instructor(s)");}

Tuesday, April 13, 2010

.NET Validators

I have been working a lot with .NET validators recently. I found this article that explains about them quite in depth: http://msdn.microsoft.com/en-us/library/aa479045.aspx

There are two new tricks I took out from this:
1. You can fire an individual validator from javascript using this: ValidatorValidate(document.getElementById("yourValidatorId")). I found it useful in this situation: I have a field taking a temperature value and they wanted to enter either in Fahrenheit or in Celsius. I made two text fields, one for Fahrenheit and one for Celsius, and one validator to validate the range of the Celsius field. When one value is entered or changed, javascript calculate and populate the other value. I didn't want to use one validator for each field because there was no room. So if I entered a value in Fahrenheit that was out of range the Celsius validator wouldn't fire until I submit the form. Now I can call the validator right after I convert Fahrenheit to Celsius so the Celsius field gets validated immediately.

2. You can use ValidatorHookupControl(control, val) to link controls to validators. It's helpful when you have a customvalidator. Without the hookup the validator wouldn't fire immediately. For example, you submit a form and then find that some control is not valid. You fix the problem but the error message won't disappear right away. The built-in validators such as requiredvalidator fires when the control is changed. So users will get confused by this inconsistent behavior, they might think they didn't fix the problem correctly.

Monday, June 29, 2009

new validation function: isValidPassword

I added a new function to the toolbox to validate a password field specifically, assuming that the password may have upper/lower case letters, numbers, or any one of a few punctuations (see actual code for reference). I'm posting about this because I added it to the ValidateAlpha class.As I did so I thought that really the Alpha is not the most accurate name as there are functions in there that validate strings beyond just alpha. However it's kind of late to rename it since it's widely called.

Just be aware that these kinds of functions may already exist before troubling yourself writing a new one!

Friday, August 22, 2008

toggleOptions

Hi guys!

Miss me? How can you miss me if I keep blogging! :P

OK so as you know I added a code library to the repo. I put all the Javascript we had already collected into it. The trouble is it's disorganized and some of it is pretty old and possible inefficient or not the best code. Therefore I hope to clean up the library to only have clean and good code :) And in an effort to do this AND organzie, from now on when I can I will add scripts into subfolders. I will label the folders by control type. Then inside the folder will be all the different scripts. So, if the JS is in a subfolder of Javascript, then it has been "quality controlled."

Please feel free to aid my efforts! Remember when you add a script to add a comment with your initials so we know who to ask if we have questions about the code!

Myself, I will try to blog whenever I add a script.

OK on to today's script. We may already have had something like this, I don't know. It was a mess in there so I didn't find it.

This function was written for those times when one of the options you pick should make all of the other options invalid. For example let's say the question is What color do you like best: red, green or none of the above? None of the above should obviously make it impossible to check red or green.

The code below is specifically for ASP:CheckBoxList, hence the part where I format the field's name as name = fieldName + "_" + i; because .NET takes the ListItem in a CheckBoxList and names it controlId_indexOfItem. If in my example the control was called cblColor then in the HTML red would have the id cblColor_0, and green would be cblColor_1 etc etc.

The parameters: optionToFocusOn is the one that triggers the function. In my example it would be cblColor_2, the none of the above. totalOptions is the total number of options, and in my example would be 3. fieldName would be the id of the control itself; in my example it would be cblColor.


//toggle options on and off - for use when one selection should disable the rest of the group
//for use with the ASP:CheckBoxList

function toggleOptions (optionToFocusOn, totalOptions, fieldName)
{
var name = fieldName + "_" + optionToFocusOn;
if (document.getElementById(name).checked == true)
{
for (i = 0; i < totalOptions; i++)
{
name = fieldName + "_" + i;
if (i != optionToFocusOn)
{
document.getElementById(name).checked = false;
document.getElementById(name).disabled = true;
}
}
}
else
{
for (i = 0; i < totalOptions; i++)
{
name = fieldName + "_" + i;
if (i != optionToFocusOn)
{
document.getElementById(name).disabled = false;
}
}
}
}

Monday, July 14, 2008

Form validation - part 2: the .NET validators

Since as we move forward, some of the team which does more of the front-end work, will start to delve more into contributing by doing some of the client-side validation, I thought it would be good to give an overview of the .NET validators. The first version of ASP.NET I worked with - 1.1 - had validator controls as part of the .NET framework. I bet they had them in the 1.0 version as well although I don't actually know for sure. Now the way these validators were supposed to work was like other .NET controls such as the datalist, or the repeater; you could just drag the control onto your page and hook it up. When the aspx made the round trip to the server and rendered in a browser, it would actually serve as client side validation of whatever field you hooked the validator control up to. The trouble was the 1.1 validators created javascript which only worked on IE. :P AND if javascript was disabled...no validation at all!

Furthermore, they were somewhat limited in what you could do with them. In the kind of forms we build, we frequently end up with skip patterns. "If you answered No to 12, go to 14" for example, meaning if you answered no to 12, 13 was not required; but if you answered yes to 12, then it WAS required. This was fairly simple javascript to create, but there existed no validator control that could handle it, except for the CustomValidator. And since we already had an extensive library of javascript functions covering most situations that cropped up, it was much simpler to just not use the validators and stick to the javascript.

In 2.0 however, Microsoft vastly improved the way these validator controls worked. Now they:

1. are cross browser compatible. WOW!
2. still work when javascript is disabled
3. have this neat option where you can tell them to ONLY turn on if the javascript is not enabled. COOL!

Our blog user known as tiger figured out how to work out #3 quite elegantly. Therefore #3 is the way we have been going, unless we don't have the hours to cover it. However as our code library goes, it is taking less and less time to even handle this task :)

Now I am going to show you a basic example. Let's say we have a form with one field with id 'greekGod' for "Favorite Greek god" and one field with id 'faveNumber' for "Favorite Number up to 20". Color is a textbox and Number is a dropdown starting with "Choose Number" for the zero index and going to 20.

Normally this might be your validation. Note that the following function actually calls 2 others, expecting them to return true or false individually. The following function is a handy way of checking numerous fields at once, and just returning false (in other words not letting the form submit) if ANY of them are invalid/have a problem:


function checkForm() <-- note it takes no arguments/parameters
{
if (
(isNotBlankAlpha(document.getElementById('greekGod'))) &&
(isSelected(document.getElementById('faveNumber'))
)
{
return true;
}

return false;
}


And this might be how you hook your form up to the javascript:


form onsubmit="return checkForm();"


If we were using the validator controls as well as the javascript, our javascript would be slightly altered:


function checkForm(source, clientside_arguments) <-- note it takes 2 arguments {
if (
(isNotBlankAlpha(document.getElementById('greekGod'))) &&
(isSelected(document.getElementById('faveNumber'))
)
{
clientside_arguments.IsValid = true;
}
clientside_arguments.IsValid = false;
}


And instead of hooking the form tag to the javascript, our aspx file would include a CustomValidator that might look like this:

asp:customvalidator id="CustomValidator1" runat="server" errormessage="" clientvalidationfunction="checkForm" onservervalidate="CustomValidator1_ServerValidate" display="Dynamic" setfocusonerror="True"


Note that it is the ClientValidationFunction property of the control that you use to tie it to the javascript. Note that you don't need the parens to call it either. However, notice that the javascript function itself now has 2 arguments. These are a mandatory signature; the source argument refers to the HTML tag that represents the validator control, and the clientside_arguments parameter refers to an object with 2 properties, IsValid and Value. The Value property is the value stored in the input control to be validated. The IsValid property must be set to false or true according to the result of the validation (Programming Microsoft ASP.NET 2.0 by Dino Esposito).

Note that the Value property is not relevant to the way we are using the CustomValidator - we are not using it to validate a single control, which is what the Value would be the value of - but instead we are validating a group of inputs all at the same time. Further, note that the javascript now takes 2 arguments - and it appears that these 2 arguments are in fact passed to the client function by the server, probably passed by the CustomValidator itself. Finally, the client function (javascript function), now that it is being tied to the CustomValidator, needs to set the IsValid property of the args parameters passed into it.

I hope this overview is somewhat helpful in explaining how to tie javascript to the ASP.NET CustomValidator control. Questions, comments, corrections are all welcome.

Form Validation - on the client side (part 1)

I just thought I'd put up a little overview on form validation. First here is a list of good articles on the subject.

http://developer.apple.com/internet/webcontent/validation.html
http://www.elated.com/articles/form-validation-with-javascript/
http://www.w3schools.com/js/js_form_validation.asp


OK, so here is my summary: whenever you are working with any form that is transmitted over the internet, you want to do some kind of validation of the input before you do anything with it. The point is not just to make sure that the input is correct - like you want to make sure a zip code has only numbers and no letters in it - but because forms are a gateway for malicious attacks on a web server. Secure forms will validate on the client side, usually using Javascript, and also on the server side, in the programming language of choice - after all not every client will have Javascript enabled.

However, for this post we are focusing on client side validation - so this is the checking that should be done before the form submits to the server. So when you are a validating a form you are doing a couple things:

1. making sure required fields are answered
2. making sure input is in a correct format

1. is self explanatory to me but more on 2:


Making Sure Input Is In a Correct Format


First, keep in mind that this should be done on ALL fields - both required and optional fields. As for what this means: you want to make sure that the input adheres to what you are expecting. Keep in mind that sometimes you can help achieve this by just designing for it. For example if you are collecting a date - don't give them a text field, give them 3 drop downs. They can't type "yesterday" if you don't give them something to type into ;)

More examples:
- SSN
- email
- phone number
- zip code
- valid range (i.e. if the answer should be 100-500, or 0 to 100%)

Let's look at SSN. To validate it, you would want to make sure that there are 9 characters, all of which are numeric. If you give the user one text field to enter SSN into, then you might start by stripping the field of all non-numeric characters, including whitespace. You would then test the length of the resulting string to see that it is 9.

This is the end of part 1. In my next post, I'll talk about doing client side validation within a .NET project that is also using the built in .NET validators.

Tuesday, July 8, 2008

validators in DCToolBox

I copied into DCToolBox a bunch of the validators that Jinghua has written. The idea is that client side validation will be run first but in a client with Javascript disabled, these server side validators will run instead. I modified a few of them, which were for optional fields, to take an optional T/F parameter. Eventually all of the validators should have this, then they can be used for both required or optional fields.

I also added some new ones, including this:


public static bool AtLeastOne(List listOfResults, string msg, CustomValidator validator)
{
bool bOK = false;
foreach (bool i in listOfResults){
if (i == true)
{
bOK = true;
break;
}
}
//check only if no true items - meaning no field was answered
if (!bOK)
{
validator.ErrorMessage += String.Format(msg);
bOK = false;
}

return bOK;
}


This is for those situations where at least one of several fields must be answered - for example if you have 4 phone number fields, at least one of them must be filled in. Check all of them, returning a bool indicating if they are answered, and then collect those bools into a List<> and send that list to this function.

I have also written a few functions for returning a simple t/f to indicate whether a field has an answer to work with the above function.

Questions? Comments? Let 'er rip! If you need an example of how to use these validators in a project then let us know and one of us can post it.