'undefined' appearing in alert - javascript

I am using Javascript to validate some code, and it works fine, but whenever I call alert to show the errors, at the beginning of the alert message I get 'undefined'. So when I should expect the alert to show 'Please enter a Low Target', instead I get 'undefinedPlease enter a Low Target'. Can somebody tell me what is wrong with my code?
//validation
var lowTarget;
var highTarget;
var errorList;
var isValid = true;
lowTarget = $('input[name="txtLowTarget"]').val();
highTarget = $('input[name="txtHighTarget"]').val();
if (lowTarget == "") {
errorList += "Please enter a Low Target\n";
isValid = false;
}
else {
if (isNumeric(lowTarget) == false) {
errorList += "Low Target must be numeric\n";
isValid = false;
}
}
if (highTarget == "") {
errorList += "Please enter a High Target\n";
isValid = false;
}
else {
if (isNumeric(highTarget) == false) {
errorList += "High Target must be numeric\n";
isValid = false;
}
}
if (isValid == true) {
if (!(parseFloat(highTarget) > parseFloat(lowTarget))) {
errorList += "High Target must be higher than Low Target\n";
isValid = false;
}
}
if (isValid == false) {
alert(errorList);
}

Assign some default value to errorList, e.g. empty string
var errorList = "";
Until you do that, initial value of errorList is undefined.

I was finding the same problem in my project while using
var try2 = document.getElementsByName("y_email").value;
alert(try2);
Now I used the following and it works well
var try2 = document.getElementsByName("y_email")[0].value;
alert(try2);
(So Be doubly sure that what you are using in correct format to use.)

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

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

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

Problem with form validation (phone numbers)

Ok, I have a validation script that checks everything on the form - but it flags the phone number fields as wrong regardless of whats in there. I've tried it a couple different ways and I cant figure out what I am doing wrong.
The part of the script that validates is...
if (testPattern(phone1, /^\d{3}$/)== false) { // checking phone length
valid = false;
}
if (testPattern(phone2, /^\d{3}$/)== false) {
valid = false;
}
if (testPattern(phone3, /^\d{4}$/)== false) {
valid = false;
}
The function code is...
function testPattern(field, reg2) {
var trueOrfalse = reg2.test(field)
if (trueOrfalse == false) {
field.style.backgroundColor="yellow"; // if false, change colors and return false
field.style.color="red";
return false;
}
else {
field.style.backgroundColor="white"; // if true, change colors and return true
field.style.color="black";
return true;
}
}
Maybe
var trueOrfalse = reg2.test(field)
should be
var trueOrfalse = reg2.test(field.value)
Added:
Also, remember that you don't have to compare to true or false when evaluating in a boolean context. (Use the value itself or the negation). And it is better to name variables after their meaning, not "trueorfalse" Here's my re-write:
if (!testPattern(phone1, /^\d{3}$/)) { // checking phone length
valid = false;
}
if (!testPattern(phone2, /^\d{3}$/)) {
valid = false;
}
if (!testPattern(phone3, /^\d{4}$/)) {
valid = false;
}
function testPattern(field, reg2) {
var good = reg2.test(field.value);
if (good) {
field.style.backgroundColor="white"; // if good, change colors
field.style.color="black";
}
else {
field.style.backgroundColor="yellow"; // if bad, change colors
field.style.color="red";
}
return(good);
}
Not an actual answer to your question, since there's nothing inherently wrong with the snippets you posted, but this was too large for a comment.
Your code is really redundant!
You could express the whole first part as:
valid = testPattern(phone1, /^\d{3}$/) &&
testPattern(phone2, /^\d{3}$/) &&
testPattern(phone3, /^\d{4}$/)
And the function code as:
function testPattern(field, reg2) {
var test_result = reg2.test(field)
if (test_result) {
field.style.backgroundColor = "white";
field.style.color = "black";
} else {
field.style.backgroundColor = "yellow";
field.style.color = "red";
}
return test_result;
}
Or even more concise:
function testPattern(field, reg2) {
var test_result = reg2.test(field)
field.style.backgroundColor = test_result ? "white" : "yellow";
field.style.color = test_result ? "black" : "red";
return test_result;
}
Isn't that much easier to read?

Categories

Resources