I'm using javascipt to validate a form and the code is like below,
function validateForm() {
console.log("start check form");
var errors = [];
var form = document.getElementsByTagName('form')[0];
/*
* Store appropriate form elements.
* There are many ways to do this, but I'm keeping it
* simple for the example
*/
var fnElem = document.getElementById("name");
var lnElem = document.getElementById("phone");
var firstName = fnElem.value;
var lastName = lnElem.value;
// etc...
// validate required fields
if (firstName === "") {
errors.push({
elem: firstName,
message: "name can't be blank"
});
}
if (lastName === "") {
errors.push({
elem: lastName,
message: "phone can't be blank"
});
}
for(var i=0; i<errors.length;i++){
alert(errors[i].message);
}
return false;
}
and in the for loop it will alert lots of times in the windows.
how can I combine all the alert into one single message..and only alert once.
I know that I can define a string and append one by one, But that seems so fool.
Is there a better way to do this.
First you map the error array to the contained messages: array.map().
Then you can join the messages: array.join().
if (errors.length) {
alert("Errors:\n" + errors.map(function (e) { return e.message; }).join('\n'));
}
Change your loop to append the message to a variable, then alert after the loop:
var messages = "";
for(var i=0; i<errors.length;i++){
messages += errors[i].message + "\n";
}
alert(messages)
for( var sAlert = '', i = 0, iL = errors.length; i < iL; ++i ) {
sAlert += errors[i].message + '\n';
}
alert(sAlert );
I didn't had a closer look at your code but if everything is fine this should solve it :)
Related
It seems i have broken my working code. The form now submit without file validation, which it should not.
document.addEventListener('DOMContentLoaded', function(){
function validate(){
var pTagMsg = document.querySelector('#ptagmsg');
var inpsText = document.querySelectorAll('.textinputs');
var inpFile = document.querySelector('#upload');
var regForm = document.querySelector('.regform');
for(let i = 0; i < inpsText.length; i++){
// check if text input fields are not filled.
let fieldValue = inpsText[i].value.length;
if(fieldValue == 0){
inpsText[i].focus();
inpsText[i].style.backgroundColor = 'red';
return false;
} else if (fieldValue != 0){
// if input fields containn values.
inpsText[i].style.backgroundColor = 'green';
}
}
var fileObjList = inpFile.files;
var fileObj = inpFile.files[0];
var fileValue = inpFile.value;
var fileName = fileObj.name;
var fileExt = fileObj.name.slice(-4);
var fileSize = Math.round(fileObj.size / 1024);
var size = 300; // size in kb.
if(fileObjList.length === 0){
pTagMsg.textContent = "Attachment Required";
pTagMsg.style.backgroundColor = 'red';
return false;
} else {
// check for extension and size.
if((fileExt == '.pdf') && (fileSize <= size)){
pTagMsg.textContent = 'file selected, OK!: ' + fileExt +', '+ fileSize;
pTagMsg.style.backgroundColor = 'green';
} else {
pTagMsg.textContent = 'file must be: '+ fileExt + 'and size of: ' + size + 'kB !';
}
}
}
// calling the submit event on the form.
regForm.addEventListener('submit', validate);
});
Firstname:
Email:
Surname:
Lastname:
ward:
location landmark:
date:
describe
First of all, I hope you can share your code in beautiful format and indentation.
When you submit form and want to do a validation, you should prevent it from its' default action. Then after all checking complete, you could continue submitting the form.
function validate(e){
e.preventDefault();
// rest of your code ...
if(everythingInvalid) {
alert("Your form invalided");
return;
}
regForm.submit();
}
regForm.addEventListener('submit', validate)
Please see others references:
Google: "validate form before submit"
Google: "submit form after preventDefault"
https://laracasts.com/discuss/channels/laravel/how-to-continue-to-submit-a-form-after-preventing-it-with-jquery
https://www.w3schools.com/js/js_validation.asp
How can I remove the first three words in java script when the response from the api I want to delete or remove the first three words.. the message from api is like below
"Error: GraphQL error: Account code already taken "
var temp = e.message
var temp1 = temp.map(function(f) {
return f.substring(temp.indexOf(' ') + 2);
});
console.log("Output", temp1)
expected output : " Account code already taken"
var st = "Error: GraphQL error: Account code already taken."
var s = st.split(' ')
s.splice(0,3)
st = s.join(' ');
console.log("Output", st)
Try this code
If the certain word like error: is present in the message then you can split the string with the word and return string from specific index:
var temp = "Error: GraphQL error: Account code already taken "
var temp1 = function(f) {
if(f.split('error:').length > 1)
return f.split('error:')[1].trim();
else return f;
};
console.log("Output:", temp1(temp))
Update: First, I will suggest you to fix the message format if possible. If you have to possible situation where the word in the message could be either error or error: then you can try the following:
var temp = "Error: GraphQL error Account code already taken "
var temp1 = function(f) {
var splitVal = 'error';
if(f.includes('error:'))
splitVal = 'error:';
if(f.split(splitVal).length > 1)
return f.split(splitVal)[1].trim();
else return f;
};
console.log("Output:", temp1(temp));
Create/modify the function to remove one word:
function removeOne(f) {
return f.substring(f.indexOf(' ') + 1);
}
and call it 3 times:
var temp1 = removeOne(removeOne(removeOne(temp)));
or in a loop:
var temp1 = temp;
for(var i = 0; i < 3; i++) {
temp1 = removeOne(temp1);
}
EDIT: wrapped the post into a snippet if someone had doubts:
var temp = "Error: GraphQL error: Account code already taken ";
/* Create/modify the function to remove one word: */
function removeOne(f) {
return f.substring(f.indexOf(' ') + 1);
}
/*and call it 3 times:*/
var temp1 = removeOne(removeOne(removeOne(temp)));
console.log("Output", temp1);
/*or in a loop:*/
temp1 = temp;
for(var i = 0; i < 3; i++) {
temp1 = removeOne(temp1);
}
console.log("Output", temp1);
const shorten = () => input.slice(21, input.length)
I am using javascript to validate my page, I have done the validation for email which should follow the basic rules of email id. But I need the validation to allow multiple email addresses. Can anyone please help in adding this. Thanks in advance.
Here is JS Code:
function function1(){
var exp = /^(([^<>()[\]\\.,;:\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,}))$/;
var emailid = document.getElementById('mailid').value;
if(emailid == '' || emailid == null){
document.getElementById('error4').innerHTML = "* Enter Email ID";
document.getElementById('mailid').focus();
return false;
}else{
document.getElementById('error4').innerHTML = "";
}
if (!exp.test(emailid)) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
}
You could do something like this:
var emails = emailid.split(",");
emails.forEach(function (email) {
if(!exp.test(email.trim()) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
});
You should split your emailid string into an array and then check the emails one by one
var emails = emailid.split(',');
You can know more about the split method here http://www.w3schools.com/jsref/jsref_split.asp
Assuming the addresses are separated by comma you could do something like this:
(untested but you should get the idea)
var theString = "an.address#domain.ext, an.other.address",
stringProper = theString.replace(/\s/g,''),
addresses = stringProper.split(','), //creates an array of every email
allValid = true;
for (var i = addresses.length - 1; i >= 0; i--) {
if (addresses[i] == 'an.other.address') {
isValid = true;
} else {
isValid = false;
}
if(!isValid) {
allValid = false;
break;
}
};
function isEmail (theString) {
var exp = /^(([^<>()[\]\\.,;:\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,}))$/;
return exp.test(theString)
}
I have this script to send automatically the load information by email:
if(confirm('', 'Are you sure?') == true) {
// enviar mails
var emails = new Array();
if (getFormFieldValue('4469') != '') {
emails[0] = getFormFieldValue('4469');
}
if (getFormFieldValue('4470') != '') {
emails[1] = getFormFieldValue('4470');
}
if (getFormFieldValue('4471') != '') {
emails[2] = getFormFieldValue('4471');
}
var msgBody = 'blablabla' ;
var s = new SendMessage();
if(emails.length > 0) {
s.sendEmailMessage(emails, msgBody);
}
confirmForm();
}
As you can see, there are 3 mails, if I don't fill the first one, nothing happen, if i complete only the second or the thirst email also nothing. The only way to executed this script is filling the first email.
How can i fix this?
Thank you
Try using an array index variable to keep track of which entry in the email array you are populating. You want to always start with index 0, then 1, etc. regardless of which emails are filled in:
var emails == new Array();
var emailIndex = 0;
if (getFormFieldValue('4469') != '') {
emails[emailIndex ++] = getFormFieldValue('4469');
}
if (getFormFieldValue('4470') != '') {
emails[emailIndex ++] = getFormFieldValue('4470');
}
if (getFormFieldValue('4471') != '') {
emails[emailIndex ++] = getFormFieldValue('4471');
}
// emails should be populated now starting from index 0
If the form field values are always incremental from 4469-4471, you can also simplify and shorten your code with a for loop:
var emails = new Array();
var emailIndex = 0;
for (var fld = 4469; fld <= 4471; fld++)
if (getFormFieldValue(fld.toString()) != '')
emails[emailsIndex++] = getFormFieldValue(fld.toString());
EDIT: As noted by #Naren, this can be made even simpler by using Array.push:
var emails = new Array();
for (var fld = 4469; fld <= 4471; fld++)
if (getFormFieldValue(fld.toString()) != '')
emails.push(getFormFieldValue(fld.toString()));
Just use Array.push(), like this:
var x = getFormFieldValue(y);
if (x != '') emails.push(x);
This can be easily used iteratively: you can for example create an array with the field values to read from and loop over it.
I have a login box using a simple javascript login comparing usernames and passwords, before you all start I know about the security issues in using javascript for authentication. Here is the code
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters", "Jonathan Goss", "Lisa Cain", "Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
document.getElementById("mandatory1").value = un;
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
At the moment if the login is successful I'm posting the username to a hidden field which is then being used by a piece of a software. How do I associate the names in fnArray with the other correct username & password so that I can then grab associated full name and post that to the hidden field "mandator1" instead?
You can get the index of the correct user
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters, Jonathan Goss, Lisa Cain, Jenny Dempsey"];
var index = 0;
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
index = i;
break;
}
}
now you can access the correct data using
unArray[index];
// and so on for other arrays
Define a variable for full name, and set it if you have the valid user:
var fn = "";
/* ... */
valid = true;
fn = fnArray[i];
/* ... */
document.getElementById("mandatory1").value = fn;
Note: Actually you can check validity later on using fn. If it is empty string, then no user was logged in. This makes it have same purpose as valid, and more.
Try this.
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = -1;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters","Jonathan Goss","Lisa Cain","Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = i;
break;
}
}
if (valid != -1) {
alert ("Login was successful");
document.getElementById("mandatory1").value = fnArray[valid];
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
set mandatory1 when the login is successful based on i (in the for loop)