javascript If Variable(s) is True - javascript

I'm not sure if I'm misunderstanding how True/False works in Javascript or not.
In my Jquery script below I'm declaring 6 variables as false.
If the regex validation conditions are good, then I redeclare the variable(s) to true.
On the bottom is a simple alert() to tell me when all variables are true.
The validation conditions are working (removing/adding classes), but the alert does not show up. That's why I'm not sure if I'm messing up the true/false part or not.
$('#password1').keyup(function() {
var checkLength = false;
var checkLetter = false;
var checkCaps = false;
var checkNum = false;
var checkSymbol = false;
var checkSpace = false;
var pswd = $(this).val();
//validate the length
if(pswd.length < 6 ){
$('#length').removeClass('valid').addClass('invalid');
}else{
$('#length').removeClass('invalid').addClass('valid');
checkLength = true;
}
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
}else{
$('#letter').removeClass('valid').addClass('invalid');
checkLetter = true;
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
}else{
$('#capital').removeClass('valid').addClass('invalid');
checkCaps = true;
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
}else{
$('#symbol').removeClass('valid').addClass('invalid');
checkSymbol = true;
}
//validate no spaces
if(pswd.match(/\s/)){
$('#spaces').removeClass('valid').addClass('invalid');
}else{
$('#spaces').removeClass('invalid').addClass('valid');
checkSpace = true;
}
// here is where I'm concerned I'm wrong
if(checkLength == true && checkLetter == true && checkCaps == true && checkNum == true && checkSymbol == true && checkSpace == true){
alert("All good");
}
});
Would someone double check me?

At first, there is no need to write checkLength == true, checkLength is enough since they are all boolean variables.
Second, in some of your conditions you assign class invalid but set the var to true, while in others you do it vice versa. Every check... = true should be in the same branch with class = valid.
Also, personally, I would adapt the validity conditions, to have all positive events either in the if or in the else branch, but not mixed like you do at the moment.
Lastly, I always try to avoid duplicate code. There are a lot of places you could refactor, but you could start easy with setting the classes in a separate function.
See it working in this fiddle.
$('#password1').keyup(function() {
var checkLength = false;
var checkLetter = false;
var checkCaps = false;
var checkNum = false;
var checkSymbol = false;
var checkSpace = false;
var pswd = $(this).val();
//validate the length
// reverse the condition, to have the valid state in the if branch as well
if(pswd.length >= 6 ){
setValid('#length');
checkLength = true;
}else{
setInvalid('#length');
}
//validate letter
if(pswd.match(/[A-Za-z]/)){
setValid('#letter');
checkLetter = true;
}else{
setInvalid('#letter');
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
setValid('#capital');
checkCaps = true;
}else{
setInvalid('#capital');
}
//validate number
if(pswd.match(/\d/)){
setValid('#number');
checkNum = true;
}else{
setInvalid('#number');
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
setValid('#symbol');
checkSymbol = true;
}else{
setInvalid('#symbol');
}
//validate no spaces
if(!pswd.match(/\s/)){
setValid('#spaces');
checkSpace = true;
}else{
setInvalid('#spaces');
}
function setValid(e){$(e).removeClass('invalid').addClass('valid')}
function setInvalid(e){$(e).removeClass('valid').addClass('invalid')}
if(checkLength && checkLetter && checkCaps && checkNum && checkSymbol && checkSpace){
alert("All good");
}
console.log("keyup");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password1" type="text">

All of these have check* = true in the wrong place:
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
}else{
$('#letter').removeClass('valid').addClass('invalid');
checkLetter = true;
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
}else{
$('#capital').removeClass('valid').addClass('invalid');
checkCaps = true;
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
}else{
$('#symbol').removeClass('valid').addClass('invalid');
checkSymbol = true;
}
Insert the statements in the block following the if (where they are deemed valid) as opposed to in the else (where they are deemed invalid):
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
checkLetter = true;
}else{
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
checkCaps = true;
}else{
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
checkSymbol = true;
}else{
$('#symbol').removeClass('valid').addClass('invalid');
}
And, although there are better ways of writing validation, this is a similar, yet more concise version of your snippet:
$("#password1").keyup(function() {
var pswd = $(this).val();
var checkLength = pswd.length >= 6;
var checkLetter = /[A-Za-z]/.test(pswd);
var checkCaps = /[A-Z]/.test(pswd);
var checkNum = /\d/.test(pswd);
var checkSymbol = /[^A-Za-z0-9]/.test(pswd);
var checkSpace = !/\s/.test(pswd);
$("#length") .removeClass("valid invalid").addClass(checkLength ? "valid" : "invalid");
$("#letter") .removeClass("valid invalid").addClass(checkLetter ? "valid" : "invalid");
$("#capital").removeClass("valid invalid").addClass(checkCaps ? "valid" : "invalid");
$("#number") .removeClass("valid invalid").addClass(checkNum ? "valid" : "invalid");
$("#symbol") .removeClass("valid invalid").addClass(checkSymbol ? "valid" : "invalid");
$("#spaces") .removeClass("valid invalid").addClass(checkSpace ? "valid" : "invalid");
if(checkLength && checkLetter && checkCaps && checkNum && checkSymbol && checkSpace) {
alert("All good");
}
});

To me, it seems that your assignments are valid statements. Whether or not they are getting set the way you want is a different matter.
It is most likely that one of the flags is not being set the way you want it to be set. To check this, you could alert each of your flags (checkCaps, etc) to confirm that each value is set the way you want. If all of the true/false is correct, then the issue would be in your final if statement.
As many people have suggested, removing the == true is a good idea. Since Javascript is dynamically typed, there is a slight possibility that it is not treating your flags as a boolean, but as something else.
If removing the == true does not work, you could check different pairs of flags to see which one makes the entire statement false.

Related

I want to stop non-alphabetical characters been put into the input

Currently I have a piece of javascript that stops the form been submitted if the inputs are empty but I want to make the script also stop non-alphabetical characters been put in too.
Here is the script
`function checkFormWhole(){
//var theForm = document.getElementById(id);
var letters = /^[A-Za-z]+$/;
var letnums = /^[A-Za-z0-9]+$/;
var theForm = document.getElementById("bookingForm");
if (theForm.customerType.value == ""){
alert("Please choose a customer type");
return false;
}
else if (theForm.customerType.value == "nonCorp" && theForm.forename.value == "") {
alert("Please Enter A Forename");
return false;
}
else if (theForm.customerType.value == "nonCorp" && theForm.surname.value == "") {
alert("Please Enter A Surname");
return false;
}
else if (checked == 0) {
alert("Please Choose An Event To Book");
return false;
}
else if (theForm.customerType.value == "corp" && theForm.companyName.value == "") {
alert("Please Enter A Company Name");
return false;
}
where i want the validation --->
else if (theForm.customerType.value == "nonCorp" && theForm.forename.value != (letters) /*|| theForm.customerType.surname.value.match != (letters)*/) {
alert("Please Enter A Forename Containing ONLY letters");
return false;
}
}`
You need to use the pattern as below.
var str = '123456';
var str2 = 'abcdEFG';
var patt = /[^a-zA-Z]/g;
// Contains non alphabet chars
if(patt.test(str) === true) {
console.log('Your input includes invalid characters')
}
// Contains alphabet chars only
if(patt.test(str2) === false) {
console.log('Your input includes valid characters')
}
You can simplify this but the example above has enough for you to be able to add the functionality you need.
Add your example to jsfiddle and if you have any problems, people can help you easier.

Add JavaScript min length validation to text field?

I'm currently using JavaScript code to validate a text field when the user types in letters a-z.
The script shows a tick if this is valid and a cross if its not. Now I am trying to add to the code to say check that the letters meet a minimum length of at least 4 characters, and if the min characters is met then show the tick and if the text is under the min character length show the cross.
How can I adjust my script to check the minimum length of the characters entered? Also can someone show me how I can allow '-' to be allowed in my validation?
script:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
if (reg.test(CnameField.value) == false)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
tried:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false)
if(input.value.length>!=len.min) return flase;
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
Almost there but you have a few syntax issues, so I've created an example test script for you:
function validateValue(value) {
var reg = /^[A-Za-z]+$/g;
var len = {min:4,max:60};
if (!reg.test(value)) {
console.log('didn\'t match regex');
return false;
}
if (value.length < len.min || value.length > len.max) {
console.log('incorrect length: ' + value);
return false;
}
console.log('correct length: ' + value);
return true;
}
validateValue('teststring');
Notice how I have set up the regex test, removing the == false? It's not needed because either false or array is returned. A true test will return true if anything other than null or false is returned.
Try this
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false) {
if(input.value.length<len.min)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
const validateCname = value => value.length < 4 ? `success message` : `error message`
function validateCname(value1)
{
var k = value1;
if(k.length<4){
//Your code if length is less than 4
}else{
//Your code if length is more than 4
}
}

validation form : how to show error message all at one time for the blank input instead of one by one?

I want to validate my form, if any of the input field is blank, the error warning will show beside the blank input field. The error message must be comes out all at one time for the blank input, not show one by one. How to do this?
Below is my javascript code :
function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}
var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}
var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}
var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}
var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}
}
You should start your function with var ok = true, and in each if-block, instead of having return false, you should set ok = false. At the end, return ok.
Here's what that might look like:
function doValidate() {
var ok = true;
var form = document.forms.form;
var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}
var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}
var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}
var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}
var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}
return ok;
}
(I've taken the liberty of changing to a more consistent formatting style, improving some variable-names, simplifying some access patterns, and replacing an alert with an inline error message like the others.)

Extending jQuery Form Validation Script for new form fields

I have a simple HTML form that originally was a series of Questions (A1 to A5 and B1 to B3) with yes/no radio buttons like this:
<tr>
<td width="88%" valign="top" class="field_name_left">A1</td>
<td width="12%" valign="top" class="field_data">
<input type="radio" name="CriteriaA1" value="Yes">Yes<input type="radio" name="CriteriaA1" value="No">No</td>
</tr>
The user could only answer either the A series of questions OR either the B series of questions, but not both. Also they must complete all questions in either the A or B series.
I now have an additional series of questions - C1 to C6 - and need to extend my validation scripts to ensure the user enters either A, B or C and answers all questions within each series.
My original script for just the A and B looks like this:
$(function() {
$("#editRecord").submit(function(){
// is anything checked?
if(!checkEmpty()){
$("#error").html("Please check something before submitting");
//alert("nothing Checked");
return false;
}
// Only A _OR_ B
if(isAorB()){
$("#error").html("Please complete A or B, not both");
//alert("please complete A or B, not both");
return false;
};
// all A's or all B's
if(allAorBChecked()){
$("#error").html("It appears you have not completed all questions");
//alert("missing data");
return false;
};
if(haveNo()){
// we're going on, but sending "type = C"
}
//alert("all OK");
return true;
});
});
function checkEmpty(){
var OK = false;
$(":radio").each(function(){
if (this.checked){
OK = true;
}
});
return OK;
}
function isAorB(){
var OK = false;
var Achecked = false;
var Bchecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
// if we have an A checked remember it
if(theChar == "A" && this.checked && !Achecked){
Achecked = true;
}
if(Achecked && theChar == "B" && !Bchecked){
if(this.checked){
Bchecked = true;
}
}
if (Achecked && Bchecked){
OK = true;
}
});
return OK;
}
function allAorBChecked(){
var notOK = false;
var Achecked = false;
$(":radio").each(function(){
// skip through to see if we're doing A's or B's
var theChar=this.name.charAt(8);
// check the A's
if(theChar == "A" && this.checked && !Achecked){
Achecked = true;
}
});
if(Achecked){
// set the input to A
$("#type").val("A");
// check _all_ a's are checked
var thisName;
var thisChecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
var checked = this.checked;
if (theChar == "A"){
if (this.name == thisName && !thisChecked){
// Yes wasn't checked - is No?
if(!checked){
notOK = true;
}
}
thisChecked = checked;
thisName = this.name;
}
});
}else{
// set the input to B
$("#type").val("B");
// check _all_ b's are checked
var thisName;
var thisChecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
var checked = this.checked;
if (theChar == "B"){
if (this.name == thisName && !thisChecked){
// A wasn't checked - is B?
if(!checked){
notOK = true;
}
}
thisChecked = checked;
thisName = this.name;
}
});
}
return notOK;
}
function haveNo(){
var thisName;
var notOK = false;
$(":radio").each(function(){
var checked = this.checked;
if (this.name == thisName){
//Is this checked
if(checked){
notOK = true;
$("#type").val("C");
}
}
thisName = this.name;
});
return notOK;
}
This worked well but I'm completely stuck at extending it to include the C series. I now have to check that the user hasn't answered any A and B, A and C and B and C questions. Everything I've tried fails to validate. Here's where I'm at right now with my new script:
$(function() {
$("#editRecord").submit(function(){
// is anything checked?
if(!checkEmpty()){
$("#error").html("Please check something before submitting");
//alert("nothing Checked");
return false;
}
// Only A or B or C
if(isAorBorC()){
$("#error").html("Please complete A or B or C, not both");
//alert("please complete A or B, not both");
return false;
};
// all A's or all B's or all C's
if(allAorBorCChecked()){
$("#error").html("It appears you have not completed all questions");
//alert("missing data");
return false;
};
if(haveNo()){
// we're going on, but sending "type = C"
}
//alert("all OK");
return true;
});
});
function checkEmpty(){
var OK = false;
$(":radio").each(function(){
if (this.checked){
OK = true;
}
});
return OK;
}
function isAorBorC(){
var OK = false;
var Achecked = false;
var Bchecked = false;
var Cchecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
// if we have an A checked remember it
if(theChar == "A" && this.checked && !Achecked){
Achecked = true;
}
if(theChar == "B" && this.checked && !Achecked){
Bchecked = true;
}
if(theChar == "C" && this.checked && !Achecked){
Cchecked = true;
}
if(Achecked && theChar == "B" && !Bchecked){
if(this.checked){
Bchecked = true;
}
}
if(Achecked && theChar == "C" && !Cchecked){
if(this.checked){
Cchecked = true;
}
}
if(Bchecked && theChar == "C" && !Cchecked){
if(this.checked){
Cchecked = true;
}
}
if (Achecked && Bchecked){
OK = true;
}
if (Achecked && CBchecked){
OK = true;
}
if (Bchecked && Cchecked){
OK = true;
}
});
return OK;
}
function allAorBorCChecked(){
var notOK = false;
var Achecked = false;
$(":radio").each(function(){
// skip through to see if we're doing A's or B's
var theChar=this.name.charAt(8);
// check the A's
if(theChar == "A" && this.checked && !Achecked){
Achecked = true;
}
});
if(Achecked){
// set the input to A
$("#type").val("A");
// check _all_ a's are checked
var thisName;
var thisChecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
var checked = this.checked;
if (theChar == "A"){
if (this.name == thisName && !thisChecked){
// Yes wasn't checked - is No?
if(!checked){
notOK = true;
}
}
thisChecked = checked;
thisName = this.name;
}
});
}elseif{
// set the input to B
$("#type").val("B");
// check _all_ b's are checked
var thisName;
var thisChecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
var checked = this.checked;
if (theChar == "B"){
if (this.name == thisName && !thisChecked){
// A wasn't checked - is B?
if(!checked){
notOK = true;
}
}
thisChecked = checked;
thisName = this.name;
}
});
}
return notOK;
}
}else{
// set the input to C
$("#type").val("C");
// check _all_ c's are checked
var thisName;
var thisChecked = false;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
var checked = this.checked;
if (theChar == "C"){
if (this.name == thisName && !thisChecked){
// A wasn't checked - is B?
if(!checked){
notOK = true;
}
}
thisChecked = checked;
thisName = this.name;
}
});
}
return notOK;
}
function haveNo(){
var thisName;
var notOK = false;
$(":radio").each(function(){
var checked = this.checked;
if (this.name == thisName){
//Is this checked
if(checked){
notOK = true;
$("#type").val("C");
}
}
thisName = this.name;
});
return notOK;
}
Anyone see what I'm doing wrong?
First of all, I think that the best usability would be to make the form easier to use, by making it harder to get wrong. If you are using javascript & jQuery, you may as well set it up so that the user has to pick a section before being able to select any items in it. You can easily support the requirement of showing all the questions, but it is a disservice to the users to allow them to perform needless work (such as filling out more than one section mistakenly) when the computer could very easily prevent this.
If you would like to see what that might look like, please comment and I will work something up for you.
In the meantime, going with your current design, here is a fiddle demonstrating one possible technique. It will work with any number of sections.
Please see that code for a full listing, but here is the script that does the heavy lifting of validation.
function validate(ev) {
var sectionsTouched = $('ol').has(':checked'),
inputs = {},
errorMessage = '';
if (sectionsTouched.length === 0) {
errorMessage = 'Please check something before submitting.';
} else if (sectionsTouched.length > 1) {
errorMessage = 'Please complete only one of sections ' + namesCommaDelimited(seriesNames(), 'or') + '.';
} else {
sectionsTouched.find('input').each(function(i, e) {
var me = $(e), name = me.attr('name');
inputs[name] = !!inputs[name] || me.is(':checked');
});
$.each(inputs, function(k, v) {
if (!v) {
errorMessage = 'Please complete all questions in your selected section.';
}
return v;
});
}
if (errorMessage !== '') {
$('#error').html(errorMessage);
ev.preventDefault();
return false;
}
return true;
}
Basic logic: if no section has a checked item, display the appropriate message. If more than one section has a checked item, too many sections have answers. If exactly one section has answers, loop through the inputs and collect a list of those that have checks for the corresponding control name. If any name exists that did not have a check, then some control group was left unchecked, and the appropriate message is displayed.
I had to take some liberties to construct a form that suits the requirements well enough for a proper demonstration. Here is what it looks like:
I hope this helps!
P.S. For the sake of completeness I would like to mention a couple of style considerations:
When you find yourself repeating code, try to abstract the repetition away--create a function, or declare a variable. For example, instead of doing $('#error').html() multiple times, set a value then do the html-setting only once.
Try to write code that doesn't secretly depend on document structure such as form field names being in a particular format (having a particular character at a position). Your javascript depends heavily on the charAt(8) function returning 'A' or 'B', and this makes it fragile--what if someone else (or even your future self) were to accidentally break the control names? Suddenly the javascript would break and the link between the two is not obvious. You can code it so you don't even need to know which section is which, as long as you have some selector that can indicate each individual section. Using a class name is okay because the class name in javascript obviously has to match the one in the html.
To greatly simplify your task, I'd suggest creating a single function that answers, for a given group: a) whether anything is checked or not; b) whether everything is checked or not. Something like:
function isAnyAllChecked(group) {
var any = false;
var all = true;
$(":radio").each(function(){
var theChar=this.name.charAt(8);
if(theChar == group && this.checked){
any = true;
}
if(theChar == group && !this.checked){
all = false;
}
});
return { any:any, all:all };
}
Now your other functions can be trivially rewritten as:
function isAorBorC() {
return (isAnyAllChecked("A").any ? 1 : 0) +
(isAnyAllChecked("B").any ? 1 : 0) +
(isAnyAllChecked("C").any ? 1 : 0) !== 1;
}
function allAorBorCChecked() {
var group = isAnyAllChecked("A").any ? "A" :
isAnyAllChecked("B").any ? "B" :
isAnyAllChecked("C").any ? "C" :
undefined;
if ( group ) {
$("#type").val(group);
return !isAnyAllChecked(group).all;
}
else
return true;
}
Notes:
You can reuse the return values of isAnyAllChecked for efficiency; I didn't do it in the code above to keep the method interfaces unchanged.
You could typecast your boolean to int (implicitly or explicitly) instead of doing any ? 1 : 0, but IMHO that way is clearer.
You also could generalize your solution to an arbitrary number of groups, using arrays and functions like map, filter etc, but for the small number of groups you have that's not really needed.
First of all i think the best approach will be to have 1 form for each section with it's own submit. You only validate if that form got all answered and that's it, the rest is discared.
<form id="formA">
<input ...
<button type="submit">Submit with A Answers</button>
</form>
<form id="formB">
<input ...
<button type="submit">Submit with B Answers</button>
</form>
etc..
BUT just in case there's a reason for why you are doing that way, here's a fiddle of how it can make it work no matter how many sections, a, b, c, d, e, f etc you have..
http://jsfiddle.net/cUfY4/
One more thing: there are several ways to resolve this problem.
The proposed Javascript is :
$('form').submit(function( e ){
e.preventDefault();
var globalAnswers = 0;
var globalComplete = false;
$('.section').each(function() {
var $this = $(this), sectionHasAnswers = false, sectionComplete = true;
$this.find('input[type="radio"]').each(function() {
var inputName = $(this).attr('name');
if ($('input[name="' + inputName + '"]').is(':checked')) {
sectionHasAnswers = true;
} else {
sectionComplete = false;
}
});
if (sectionComplete && !globalComplete) {
globalAnswers++
globalComplete = true;
} else {
if (sectionHasAnswers) {globalAnswers++};
}
});
if (globalAnswers == 1 && globalComplete) {
// EVERYTHING OK! SUBMIT FORM!
} else {
// ERRORS use globalAnswers and globalComplete for exact problem
}
});

Form Validation - How to use If and Else If

I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...

Categories