Loading form input fields into a javascript array and then validating - javascript

I seem to be really stuck on something. I have a function to check if all the form input fields are equal to null or "" which is all fine but wanted to see if there is another way of doing it by loading all the fields into a javascript array and then doing a for loop along with an if statement to check if any of the fields are empty, unfortunately I can't seem to get this to work and wondering if I've simply just missed something some where. Here is my code:
function checkempty()
{
fname = document.getElementById("firstname").value;
lname = document.getElementById("lastname").value;
fage = document.getElementById("age").value;
addressl1 = document.getElementById("addressline1").value;
addressl2 = document.getElementById("addressline2").value;
ftown = document.getElementById("town").value;
fcounty = document.getElementById("county").value;
fpcode1 = document.getElementById("pcode1").value;
fpcode2 = document.getElementById("pcode2").value;
ftelephone = document.getElementById("telephone").value;
fcomment = document.getElementById("comment").value;
var myArray = [];
myArray[0] = fname;
myArray[1] = lname;
myArray[2] = fage;
myArray[3] = addressl1;
myArray[4] = addressl2;
myArray[5] = ftown;
myArray[6] = fcounty;
myArray[7] = fpcode1;
myArray[8] = fpcode2;
myArray[9] = ftelephone;
myArray[10] = fcomment;
for(i=0;i<myArray.length;i++)
{
if(!myArray[0])
{
return true;
}
}
return false;
}
I then use another function:
function checkform()
{
if(checkempty)
{
display_errormessage("One or more fields empty!");
}
else
{
alert("Thanks for you input!");
}
}
The display_errormessage() function is just one that puts an error message into a div at the top of the form to display an error message if the form is incomplete.
Can anyone see where i've gone wrong?
Thanks in advance for any help!
Dave.

First, function checkform is not called. The if (checkform) should be if (checkform()) or you will test only test the availability of the function, not the result.
Then the if (!myArray[0]) should be if (!myArray[i]) to not only test the firstname
Or better, if (myArray[i].length==0) to be sure to explicitly test for empty string and not just doing an implicit boolean conversion (javascript evaluate 0=="" as true)

if(!myArray[0]) should be if(!myArray[i]), but a larger point is you're only validating that the value isn't falsey (null, '', 0, false, etc.), not that it's appropriate for the task.

Guess you won't need this function as you've already fixed yours, but I'll leave it here as it may be helpful in the future. JSFiddle
function checkform()
{
arr1 = document.getElementsByTagName('input');
arr1 = Array.prototype.slice.call(arr1);
arr2 = document.getElementsByTagName('textarea');
arr2 = Array.prototype.slice.call(arr2);
arrs = arr1.concat(arr2);
for(i=0;i<arrs.length;i++)
{
if (arrs[i].type == "text" || arrs[i].type == "textarea")
{
if (arrs[i].value == '')
{
alert("Fill all fields before submitting!");
return false;
}
}
}
alert("Thanks for your input!");
return true;
}

According that your input fields are in the form named form:
var allTrue = [].every.call( document.forms.form.elements, function( el ) {
return !!el.value;
} );
if ( allTrue ) {
alert( "Thanks for your input!" );
}
else {
alert( "Some fields are missing!" );
}

Related

How to set CRM javascript value to null?

I have the following JavaScript code in a Dynmaics library, however the code does not set the value to null in the else condition any ideas to why? I believe my code is correct.
Please advise. My null setting isnt working I also tried removeAttribute();it does not work
function validateSortCode(executionContext) {
var formContext = executionContext.getFormContext();
var sortcode = formContext.getAttribute("sortcodee").getValue();
var errorId = "error";
if(sortcode != "")
{
var sortcoderegex = /^(\d){2}-(\d){2}-(\d){2}$/;
if(sortcoderegex.test(sortcode) == false)
{
formContext.ui.setFormNotification("Please ensure correct format of Sort Code i.e. 12-34-56", "ERROR", errorId);
}
else
{
formContext.getAttribute("sortcodee").setValue(null);
//formContext.getAttribute("sortcodee").removeAttribute("sortcodee");
}
}
}
You need to set the value after your notification of the error to null.
Try this.
function validateSortCode(executionContext) {
var formContext = executionContext.getFormContext();
var sortcode = formContext.getAttribute("sortcodee").getValue();
var errorId = "error";
if(sortcode != "")
{
var sortcoderegex = /^(\d){2}-(\d){2}-(\d){2}$/;
if(sortcoderegex.test(sortcode) == false)
{
formContext.ui.setFormNotification("Please ensure correct format of Sort Code i.e. 12-34-56", "ERROR", errorId);
formContext.getAttribute("sortcodee").setValue("");
}
else
{
formContext.ui.clearFormNotification(errorId);
}
}
}
The above should do the trick

How can I create a function to validate an email and a username with a Javascript?

I'm very new in coding. I'm creating a newsletter form and I'll need people to register by entering a name (only letters) and a valid email address.I'm trying to create a javascript function but it does not work properly. Function is:
function validaIscrizione(username,email) {
var nameRegex = /^[a-zA-Z\-]+$/
var emailRegex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if(
username==''|| username==undefined || nameRegex.test(username)||
email== '' || email == undefined || emailRegex.test(email)
)
{return false;}
else{return true;}
}
var button = document.getElementById('btn_1');
button.onclick=function(){
var login=document.getElementById('username').value;
var password=document.getElementById('email').value;
var result = document.getElementById('result');
if(validaIscrizione(username,email)){
result.innerHTML = "Grazie per aver effettuato la registrazione";
}else{
result.innerHTML = "Dati non validi";
}
}
"
am I missing something? Thank you in advance
I modify a little your validate function and put comments with the explanation:
function validaIscrizione(username, email) {
const nameRegex = /^[a-zA-Z\-]+$/;
const emailRegex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// here you use short circuit for the falsy values like "" or undefined and validate the regex
const isUsernameValid = username && nameRegex.test(username);
const isEmailValid = email && emailRegex.test(email);
// here you return that is valid only if the two inputs pass your tests
return isUsernameValid && isEmailValid;
}

jQuery check multiple CSV lists

To simplify my problem i rewrote the code without the parsing of CSV, but instead with a variable that holds the data.
--CODE EDIT---
$(document).ready(function() {
var qID = 'xxx';
var source = ['text1', 'text2', 'etc3'];
var source2 = ['text4', 'text5', 'etc6'];
$('#question' + qID + ' input[type="text"]').change(function() {
var validVal = 0;
var inputVal = $(this).val();
// Loop through the text and test the input value
$(source).each(function(i) {
if (inputVal == this) { // If a match is found...
validVal = 1;
}
});
// If a valid text was entered
if (validVal == 1) { // A valid input
alert("GOOD");
} else { // An invalid input
alert("NOT GOOD");
}
var validVal2 = 0;
var inputVal2 = $(this).val();
$(source2).each(function(j) {
if (inputVal2 == this) { // If a match is found...
validVal2 = 1;
}
});
// If a valid text was entered
if (validVal2 == 1) { // A valid input
alert("GOOD2");
} else { // An invalid input
alert("NOT GOOD2");
}
});
});
The script works fine for one source (var source) but i want to check in the same text field 2 variables (source, source2) that will produce different alerts.
The script is run through a limesurvey form and the input is a simple [type="text"] field.
How do I check for 2 different arrays of text in the same text field?
Whenever you find yourself putting counters on variable names to create a series, you need to stop and think about what you are actually doing there. Making counted variable names is always wrong.
Use arrays.
var qID = 'xxx';
var source = [];
source.push(['text1', 'text2', 'etc']);
source.push(['text1', 'text2', 'etc44']);
source.push(['text15', 'text25', 'etc454']);
$('#question' + qID + ' input[type="text"]').change(function() {
var valid = false;
var inputVal = $(this).val();
$.each(source, function(i, terms) {
$.each(terms, function(i, term) {
valid = inputVal === term;
return !valid; // returning false stops the .each() loop
});
return !valid;
});
if (valid) {
alert("GOOD");
} else {
alert("NOT GOOD");
}
});
A more appealing way to express the nested loop above uses built-in methods of Array.
var valid = source.some(function (terms) {
return terms.includes(inputVal);
});
in ES6 syntax this can be made a one-liner:
var valid = source.some(terms => terms.includes(inputVal));

Validate forms using javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

JavaScript form validation improvement

I have a user profile form with 15 text fields and some dropdown and an textarea. the scene is that user can input field in profile form. On save it is no necessary to fill all fields, whatever the user fills in fields i have to validate and save in database via ajax call.
for now i am using validation like this,
var first_name = document.getElementById('id_candidate_profile-first_name').value;
....
var status = false;
if(first_name != ''){
status = regex_test(first_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-first_name').innerHTML = "first name should only have alphabets";
}
else{
status = true;
}
}
if(middle_name != "" & status = true){
status = regex_test(middle_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-middle_name').innerHTML = "middle name should only have alphabets";
}
else{
status = true;
}
}
if (last_name != '' & status = true){
status = regex_test(last_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-last_name').innerHTML ="last name should only have alphabets";
}
else{
status = true;
}
}
if (date_of_birth != '' & status = true){
status = regex_test(date_of_birth, ck_date);
if(status==false){
document.getElementById('candidate_profile_error-date_of_birth').innerHTML ="date of birth should be in YYYY-MM-DD format";
}
else{
status = true;
}
}
if (birth_place != '' & status = true){
status = regex_test(birth_place, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-birth_place').innerHTML ="birth_place should only have alphabets";
}
else{
status = true;
}
}
if (nic != '' & status = true){
status = regex_test(nic, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-nic').innerHTML ="nic should be in this format 12345-1234567-1";
}
else{
status = true;
}
}
if (status = true) {
// made ajax call
}
function regex_test(variable, regex){
var _result = false;
if(!regex.test(variable)){
_result = false;
}
else {
_result = true;
}
return _result;
}
Can be seen that there are lots of nested if else involved that irritate me, need some better way to do this? any best alternative?
You could create an array of validation objects, each object containing properties reg_ex, field, error_msg_container_id and error_msg:
var validationRules = [
{ reg_ex: first_name,
field: ck_name,
error_msg_container_id: candidate_profile_error-first_name,
error_msg: "first name should only have alphabets" },
{ reg_ex: date_of_birth,
field: ck_date,
error_msg_container_id: candidate_profile_error-date_of_birth,
error_msg: "date of birth should be in YYYY-MM-DD format" }
];
In the validation function, you just iterate through the whole array. That also makes it easier to maintain further input fields which you might add later.
P.S.: If you don't know how to iterate over an array, let me know.
Edit: Since requested by OP, an iteration function would look similar to this:
function isFormDataValid() {
for (i=0; i< validationRules.length; i++) {
// do the validation inside here, it will be repeated once for each validation rule;
}
return status;
}
In case you need variable property names from the array to read/write, use this syntax
Object[variable]
where variable contains the string that is the name of the property you need to access.
var myObject = {
name: "peter",
age: 46
};
var validationRules = [ { fieldname: 'name'}, { fieldname: 'age' } ];
for (var i=0; i< validationRules.length; i++) {
alert(myObject[validationRules[i].fieldname]);
}
You can use any form validation library. I personally recommend Parsley.
There's a simple validation form example: http://parsleyjs.org/doc/examples/simple.html

Categories

Resources