How do I Validate Arrays? - javascript

I have a form which has 4 columns and the user can dynamically add or delete rows.
Now I tried to validate this through javascript following code:-
<script type="text/javascript">
function chkempty()
{
var x=document.forms["main"]["qty[]"].value
var y=document.forms["main"]["price[]"].value
var z=document.forms["main"]["item[]"].value
if (x==null || x=="") {
alert("Quantity must be filled out");
return false;
}
if (y==null || y=="") {
alert("Price must be filled out");
return false;
}
if (z==null || z=="") {
alert("Itemcode cannot be empty");
return false;
}
}
It works for the first row but when the user selects more than one row, even after filling up values, he is getting the validation error message. can someone help me with this please?
Thanks and keep smiling.

VERY simple solution here:
Use Jquery Inline Validator
When you add new lines of content to the table, simply ensure that you have the proper class defined (such as class="validate[required,custom[email]]" ) to ensure that it will validate the field correctly as you wish. I often just do the required element, but the example I gave above also does email format checking. There are additional built in checkers for phone numbers, currency, etc.
If the user messes up an input, it will display a visually appealing tooltip like dialog next to the field with the error.
Done. Simple. Clean. Fast.
None of these solutions make up for the fact that you really need to sanitize on the server-side as well. Any Javascript can be bypassed, so it's not 100% guaranteed to be safe or accurate. But it is a good start and provides quality, instant feedback to the user.

var x=document.forms["main"]["qty[]"].value
You should loop over the elements and validate each value, instead of trying to get a value from an array, I guess.
var x=document.forms["main"]["qty"];
for ( var i=0, len=x.length; i<len; ++i ){
// validate the value of the current element.
}
EDIT: added a small example.

document.forms.form_id.control_name will return either an HTMLElementNode or a NodeList depending if there are one or many matching elements.
You can do something like:
var x=document.forms["main"]["qty[]"]
if (x.nodeName) {
// Is a Node. Work with its value
} else {
// Is a NodeList, loop over it with for
for (var i = 0; i < x.length; i++) {
var node = x[i];
// Work with its value
}
}

Related

Most efficient js/jquery way to prevent submission of empty fields (including spaces)

I have an advanced search form in a custom CMS. I need to check to make sure that the user doesn't try to submit the form without at least one field populated. No problem; this is a very stripped-down version:
var noText = false;
if(!$('#advancedId').val() && !$('#advancedTitle').val() &&
$('#advancedCoupon').val() && !$('#advancedDesc').val() ) {
noText = true;
}
if(noText) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
noText = false;
return false;
}
But we have that one QA guy who just has to really do his job, and deliberately tries searches that there's no way our client would ever do. He submitted a bug indicating that if he entered a space in every field, it passes and tries to submit.
So I tried trimming the values like this:
if(!$('#advancedId').val().trim() && !$('#advancedTitle').val().trim() &&
$('#advancedCoupon').val().trim() && !$('#advancedDesc').val().trim() ) {
noText = true;
}
This of course works if I actually enter a space in all of the fields, but throws a "Cannot read property 'trim' of null" error if I try to submit it with a space in one field, and nothing in the others.
Yes, I could do something like this:
if($('#advancedId').val()) {
$('#advancedId').val($('#advancedId').val().trim());
}
Yes, I could make it somewhat shorter with a terniary, but I'd still have to do that for over a dozen fields. Is there a better way to do this?
I would probably select them all and then do a filter. Though to make it less tightly coupled, I'd probably put a class on them and select with that instead of all the ids.
//select all the fields concerned and filter on them for non-blank values
var nonBlankFields = $('#advancedId, #advancedTitle, #advancedCoupon, #advancedDesc').filter(function(){
//default to an empty string if for some reason the value doesn't exist
return ( this.value || '' ).trim().length > 0
});
if (!nonBlankFields.length) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
return false;
}

Javascript Empty check

So, i have this code but something doesn't seem to work as expected.
function validateForm() {
var x = document.forms["reg"]["username","password","first_name","last_name","age","mail"].value;
if (x==null || x=="" || x==0) {
alert("All fields must be filled out");
return false;
}
}
I get an alert if I leave any of the fields empty. Except for the last one. If I fill in every field except for mail, I can proceed. And if I only fill in mail, I can proceed as well.
How come it checks all the fields except the last one?
Or might there be an easier way to check if the fields are filled in? (I'm actually using PHP but somehow the if(empty($_POST['username']) thing doesn't work anymore, so I figured to just use JS, since it looks better with the alert message anyway.
You need to break your function up a little bit - put the field names into an array and loop through them one by one. And as stated in the comments, the null check isn't required.
function validateForm()
{
var fields = ["username", "password", "first_name", "last_name", "age", "mail"];
for(var i = 0; i < fields.length; i++)
{
var fieldName = fields[i];
var x = document.forms["reg"][fieldName].value;
if (x == "" || x == 0) {
alert("All fields must be filled out");
return false;
}
}
}
You should also do the same validation in your PHP code, as someone could easily disable JavaScript and so the data wouldn't get validated at all.
You cannot get the whole thing in an array! Instead you need to do it differently. It takes only the mail one as that's the last one in the list. So, you can do something like this:
x = [];
x.push(document.forms["reg"]["username"].value);
x.push(document.forms["reg"]["password"].value);
x.push(document.forms["reg"]["first_name"].value);
x.push(document.forms["reg"]["last_name"].value);
x.push(document.forms["reg"]["age"].value);
x.push(document.forms["reg"]["mail"].value);
And that you have built that array, you need to check for "" and 0 values in them. You need to write a function like in_array() of PHP to JavaScript to check for empty and 0 values.
Instead of all these hassles, you can happily use a jQuery form validator plugin, and it does the work well.

Checkbox checked with javascript does not POST

I have an array of 27 checkboxes generated using php. Checking the checkboxes manually works perfectly. The checkboxes are placed in an html table (other tabular dated is included), (all inside the form tags) with name="chk[]' and value='Index Number' of the array (0-27) in the usual form of
When I execute a typical Java-script "Check All" function (from a link_click or button_click) the check boxes all display the check-boxes as 'checked'. But, nothing gets submitted. Print_r shows the 'chk' array is indeed empty when I submit!
If I set the check-boxes manually, $_POST('chk') array IS posted, and everything works as expected.
It appears that when checking the check-boxes with Javascript, ¡checked' values don't get posted.
Print_r confirms the 'chk' array is empty whenever the 'displayed' value was set using Javascript!
Can anybody attempt to explain to me why the 'displayed value' of the checkbox is not reflected by, or included in the post?
The page validates on W3C Ok and I have crawled over my code and cannot find any likely errors. Platform is Win7/Wamp Sever/Firefox. Google/StackOverflow search does not reveal any similar symptoms/solutions.
Many thanks in advance for anyone with an idea on the problem.
The javascript CheckAll function I am using is -
function checkall(frm) {
for (var i=0; i<frm.elements.length; i++) {
if (frm.elements[i].name = "chk")
{frm.elements[i].checked = true;}
}
}
The array of 27 check-boxes is in the normal array format, with 'value' being the array Index.
<tr><td><input type='checkbox' title='' name='chk[]' value='6' ></td> text label </tr>
You have two errors in your if condition.
It's not even a condition, it's an assignment statement (conditions are written with
double equal signs)
Element name should be compared to chk[] instead of chk
Your checkall function should be:
function checkall(frm) {
for (var i=0; i<frm.elements.length; i++) {
if (frm.elements[i].name == "chk[]")
frm.elements[i].checked = true;
}
}
Now you might be wondering what the hell does this have to do with the values not being submitted, and why are they checked, I can explain.
Your current code is assigning a new name "chk" to the checkbox elements (see reason 1 why your condition is not even a condition), and since it's not a condition, the if statement is always true, and the code segment that sets the checked value to true is being executed and that's why you can see the elements checked. Now when you request $_POST['chk[]'] in your PHP you get nothing because the elements' names were all changed to 'chk' by your supposedly (if "condition").
iSWORD has a complete answer, this is just some additional hints. You can simplify the function by taking advantage of built–in browser features:
function checkall(frm) {
var cbs = frm['chk[]'];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
cbs[i].checked = true;
}
}
Form controls are available as named properties of the form. Where more than one control shares the same name, an HTML collection is returned. So in the above, cbs is a collection of all the controls with a name of 'chk[]'.
To account for cases where there might be zero, one or more same–named controls, use:
function checkall(frm) {
var cbs = frm['chk[]'];
if (cbs) {
if (typeof cbs.length == 'number') {
for (var i=0, iLen=cbs.length; i<iLen; i++) {
cbs[i].checked = true;
}
} else {
cbs.checked = true;
}
}
}
You could also use querySelectorAll, which always returns a collection (but might not be available everywhere) and use the following with the first function:
var cbs = document.querySelectorAll('input[name="chk[]"]');
You can try using this function
Javascript
function checkall(formname,checkname,thestate){
var el_collection=eval("document.forms."+formname+"."+checkname)
for (c=0;c<el_collection.length;c++)
el_collection[c].checked=thestate
}
HTML
Check All
Uncheck All

Basic form validation with Javascript

I am trying to understand the function at (http://www.w3schools.com/js/js_form_validation.asp) and rework it (below) using getElementsByClassName to find a class attribute I added to an HTML input tag. I'm very new to Javascript, and I do not understand why I have to add .value (W3 example) or .view (my example) to the end of the statement below in order for it to work. As I understand it the first statement in the function says look in the document, and assign the variable X, to any input fields with the class attribute reqname.
Thank you.
MY FUNCTION:
function validateForm()
{
var x=document.getElementsByClassName("reqname").view;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
FUNCTION AT W3:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
A form element such as an input field typically has a value, that is the string that has been entered into the input field.
By specifying .value, they explicitly check whether the content of the element is null. Without it, they'd be checking if the element itself is null, i.e. if the element exists.
Your code has some further issues. .view that you're using doesn't make sense. Also, getElementsByClassName returns a list of elements, rather than a single element, so you won't be able to immediately access its .value.
If you know that there's just the one element, you could check getElementsByClassName("reqname")[0].value. If you want to validate the value of all "reqname" fields, you'd have to iterate over your collection and check each item individually:
var elements =document.getElementsByClassName("reqname");
for(var i = 0, l = elements.length; i < l; i++) {
var x = elements[i].value;
if(x == null || x == '') {
alert("First name must be filled out");
return false;
}
}
the input field has more properties than just it's 'value' (which is the text being written in it). So you'll have to state which property you want to access by appending the name (in your case 'value') with a '.'.
If you really want to do form validation, also be sure to do it in your php file as well ! Everything javascript does is on the client side, so people can - basically - ignore it and just send some random data to your .php file.
may be useful to:
http://tetlaw.id.au/view/javascript/really-easy-field-validation
jquery-plugin
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
it's more simple to write
function ValidateForm() {
var x = $("#inputOID").val();
if (x == null || x == "")
alert("......");
return false;
}
so your function is ValidateForm. You declare a variable x, and give the value from an input by the input ID. For example <input id="inputOID" .... />. So x will contain the value of the input. The you verify if is null or empty, and if is you will alert the user.
Thats all! Good luck!

How can I stop isNaN from returning an error for a blank field?

EDIT:
Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,
When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?
I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:
var checkNumber = function (testval) {
if ( isNaN(testval) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).
Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:
var checkNumber = function () {
if ( isNaN( this.value ) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
And then (with a naive binding approach by ID):
document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
Can't you just initialize the text box with a default value, say 0?
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.
Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars
How about use short-circuit evaluation with jsFiddle example
EDIT for parseFloat:
function checkNumber()
{
var sInput = parseFloat(document.getElementById('sInput').value || 0);
var dInput = parseFloat(document.getElementById('dInput').value || 0);
var pInput = parseFloat(document.getElementById('pInput').value || 0);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please press 'Reset' and enter a number.");
}
}
So if pInput is undefined just use 0, but if the input has value then use that value.
SIDE NOTE: white space is actually a number, +' '; // 0

Categories