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!
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;
}
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.
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
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
}
}
I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}