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.
Related
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;
}
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
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!
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
}
}
On a form, I need to make sure that all fields are filled in and that the phone # and email address are valid. I tried using a jQuery validation plugin but it changed the page's look and feel. The plugin also was dynamically looking for some css files in some spot that was unexpected.
I love jQuery but the plugin seemed too much for what I wanted.
Since all I need to do is to make sure the fields are not empty and that the phone number is valid and email is valid, what javascript functions do you suggest? I will still use jQuery core.
Serverside we want to use apache commons PhoneNumberFormatter and same with email validation.
Thanks!
I think you're looking for JavaScript regular expressions, using the RegExp object that comes as a standard part of JavaScript. You can use that to perform basic checking of email addresses and phone numbers.
e.g.
function emailIsValid(emailAddress) {
var emailRegex = /\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/;
return !!emailAddress.match(emailRegex);
}
The code above is not tested, but it should give you an idea of how to do it. Just do the same again for the telephone number, and then do something like this:
if (emailIsValid(emailAddressValue) && telephoneNumberIsValid(telephoneValue)) {
//Submit form
} else {
alert ("There are errors on the form, please correct and invalid data");
}
In this jsfiddle you'll find a JQueryless method I use to check form fields. It checks all form fields periodically using an interval function.
Everyone focused on the email and phone number validation, but encase you need help with detecting empty text boxes and even just how/when to call the code for email/phone validation:
<script type="text/javascript">
function validate()
{
var curVal;
for(var index = 1 ; index < 15 ; index++)
{
curVal = document.getElementById("textbox_"+index).value
if(curVal == "")
{
alert("empty text box")
return(false); //false will stop the form from submitting
}
if(index = 5)// email text box
{
//validate email
}
}
}
</script>
<type="input" id="textbox_1">
<type="submit" value="Submit" onClick="validate()">
here is one for email
function checkemail()
{
var str=email
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z] {2})?)$/i
if (filter.test(str))
testresults=true
else
{
alert("Please input a valid email address!")
testresults=false
}