What would a JavaScript script be that, on submit, gets all form elements with class="required" and if they're empty, displays an alert box, "you must fill out so-and-so"?
I was thinking of an if-else, and in the if section we would get a while that loops through all the class=required elements, and the else would submit the form.
There are many many JavaScript libraries on the internet that do exactly this.
Try this one:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Or try a Google search for JavaScript Form Validation.
It is fairly easy to loop over the elements of a form and check that those with a certain class have a value that meets certain criteria:
<form name="f0" onsubmit="return validate(this);">
<input name="inp0" class="required" >
<input name="inp2" class="required" >
<input type="submit">
</form>
<script type="text/javascript">
var validate = (function() {
var reClass = /(^|\s)required(\s|$)/; // Field is required
var reValue = /^\s*$/; // Match all whitespace
return function (form) {
var elements = form.elements;
var el;
for (var i=0, iLen=elements.length; i<iLen; i++) {
el = elements[i];
if (reClass.test(el.className) && reValue.test(el.value)) {
// Required field has no value or only whitespace
// Advise user to fix
alert('please fix ' + el.name);
return false;
}
}
}
}());
</script>
The above is just an example to show the strategy.
Using an alert is less than optimal, usually an area is set aside adjacent to the required fields so that error messages can be written there to direct the user's attention to the invalid fields. You can also set all the error messages in one go, then return, rather than one at a time.
Edit—updating multiple errors
Have an element adjacent to each control to be validated with an id like the element's, so if an input is called firstName, the error element might have an id of firstName-err. When an error is found, it's easy to get the related element and put a message in it.
To do all at once, use a flag to remember if there are any errors, say "isValid" that is set to true by default. If you find any errors, set it to false. Then return it at the end.
Using the example above, the HTML might look like:
<input name="firstName" class="required" >
<span id="firstName-err" class="errMsg"></span>
Errors for firstName will be written to firstName-err.
In the script, if an error is found:
// At the top
var isValid = true;
var errEl;
...
// When entering the for loop
el = elements[i];
errEl = document.getElementById(el.name + '-err');
// when error found
isValid = false;
if (errEl) errEl.innerHTML = '... error message ...';
// else if error not found
// remove message whether there is one or not
if (errEl) errEl.innerHTML = '';
...
// At the end
return isValid;
You can also use a popup to show the errors, however that is really annoying and the users must dismiss the popup to fix the errors. Much better to just write next to each one what is wrong and let the user fix things in their own time.
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;
}
Need help getting this function to:
Validate data format
Validate data is existing
Focus on missing fields (One at a time is fine)
The function below is updated from some advice. It works much better then my original. Problem though is if email field is blank it works great, wont move on until value is put in. But the other fields will focus correctly, but still allow the func to move to else, which just lowers opacity as you can see.
function quantity_box() {
// store all your field names in an array
var fieldNames = ["EMAIL", "BILLTOFIRSTNAME", "BILLTOLASTNAME"];
// loop over each field name in that array
for (var i = 0; i < fieldNames.length; i++) {
// extract the field name
var fieldName = fieldNames[i];
// use the field name to index the form object and get the field itself
var field = document.forms["billing_form_id"][fieldName];
// check the field's value to see if it's empty
if (field.value === '') {
field.focus();
// break from our loop, since we've already found an invalid value
break;
}else{
$(".prod_billing_box").delay(0).animate({"opacity": "0"}, 200);
$(".prod_quantity_box").delay(215).animate({"opacity": "1"}, 200);
}
}
Also a note. Even though fields like EMAIL have settings like TextMode="Email" to verify proper format, the above function also ignores that.
You've misunderstood how indexes work. The following line is valid, but not doing what you expect it to.
["EMAIL" && "BILLTOFIRSTNAME" && "BILLTOLASTNAME"]
What this is actually doing is performing a boolean expression using and operations, like you would in an if statement. If you actually run that line in your javascript console, it will print out
"BILLTOLASTNAME"
Which is still valid, but not what you want.
Instead, you need to loop over all the form fields and check each one to make sure it's valid. If any of the fields are invalid, you can break out of the loop.
// track if the entire form is valid, start true
var allValid = true;
// store all your field names in an array
var fieldNames = ["EMAIL", "BILLTOFIRSTNAME", "BILLTOLASTNAME"];
// loop over each field name in that array
for (var i = 0; i < fieldNames.length; i++) {
// extract the field name
var fieldName = fieldNames[i];
// use the field name to index the form object and get the field itself
var field = document.forms["billing_form_id"][fieldName];
// check the field's value to see if it's empty
if (field.value === '') {
field.focus();
// our entire form isn't valid
allValid = false;
// break from our loop, since we've already found an invalid value
break;
}
}
// if we make it this far and allValid is still true...
if (allValid) {
// perform your "else" code here
}
One possibility worth noting is that all of this can be done with no javascript whatsoever using HTML5 form field validators. As long as you wrote your form fields in a <form> tag, you can add validators such as required to a field and the form will not submit, as well as display validation warnings, until the validators all pass. Below is a working example.
<form>
<input type="text" required placeholder="Must fill me in"><br/>
<input type="checkbox" required> Must be checked<br/>
<input type="radio" name="radiogroup" required> One must be chosen<br/>
<input type="radio" name="radiogroup"> One must be chosen 2<br/>
<input type="email" placeholder="Must be an email if filled"><br/>
<br/>
<button type="submit">Submit</button>
</form>
It's also possible to query the form element itself and as it if it's valid, as well as use :valid CSS form selectors to style valid and invalid fields.
This might be a bit confusing but bear with me.
I need 2 textbox and 1 checkbox.
When the checkbox is checked, it needs to check whether the textboxes are filled or not.
If the textboxes are filled in, it will do nothing.
I'm really struggling with this so I would really appreciate it.
If you don't understand what I even said, here's the question that I need to solve.
*In page order.html, create a checkbox with label “same as delivery address” somewhere appropriate near the fields for billing address. When this checkbox is checked, the fields for billing address will be filled with the delivery address automatically. If the delivery address is not completed when this checkbox is checked, display an alert or inline message: “Please enter your delivery address first”. *
I've managed to do the duplicate part with these codes.(address and post codes are separated)
function copy() {
var daddress = document.getElementById("daddress");
var baddress = document.getElementById("baddress");
baddress.value = daddress.value;
var dpost = document.getElementById("dpost");
var bpost = document.getElementById("bpost");
bpost.value = dpost.value;
}
But I cannot figure out the part after this.
Here's the code for the checkbox
<input id="duplicate" type="checkbox" name="duplicate"
value="Duplicate" onClick="copy();"/>Same as delivery address
<p id="dalert"><b><i>Please enter your delivery address first</i></b><p>
In this case you could use a textarea for the address:
<textarea id="delivery-address"></textarea>
Then you would use JavaScript to get the contents of it with:
var deliveryAddress = document.getElementById("delivery-address").value.trim();
To check if they entered an address, you would use:
if (deliveryAddress === "") { ... }
In most cases, the address would be broken up into several inputs, often two lines for the street address, an input for city, state and postal code.
An alert is displayed like so:
alert('Some text');
You can use an if statement to check whether there's any input before setting them.
if (daddress.value && dpost.value) {
baddress.value = daddress.value;
bpost.value = dpost.value;
} else {
alert('Please enter your delivery address first!');
e.preventDefault(); // Stops checkbox from becoming checked.
}
JSFiddle
Edit: Forgot to mention that to use e.preventDefault(), you need to change your function to accept the e parameter (function copy(e) {...}) and pass event in your onclick event (onclick="copy(event)"). You'll see those in the JSFiddle.
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 PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";