Combining 2 IF/ELSE statements (validation) - javascript

I am trying to combine 2 IF/Else statements to create one validation function. This is my code for the 2 separate validations:
function validateCarsMin(v){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
return '1B cannot contain a value if CW is entered';
}
} else return true
}
function validateRateLoc3(v){
if (v != ''){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
return 'This Value is not valid';
}}
}
I did not know if there was a best practice for this and it so, what would it be?
Thanks for the help on the last question I had.

Change the functions to return either true or false. You can push the msgs to an array to be used later.
var errorMsgs = [];
function validateCarsMin(){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
errorMsgs.push('1B cannot contain a value if CW is entered');
return false;
}
} else{
return true;
}
}
function validateRateLoc3(){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
errorMsgs.push('This Value is not valid');
return false;
}};
}
function validateForm(){
var isValid = false;
isValid = validateCarsMin();
isValid = (!isValid) ? isValid:validateRateLoc3();
return isValid;
}
Note I removed the v parameter because it seemed irrelevant. It is not used in the first function and it creates a syntax error in the second.

Related

exporting function return value

I have a code below
function createRoom(){
$(document).keyup(function(event) {
if ($("#room_name").is(":focus") && event.key == "Enter") {
var plainText = document.querySelector(".create-room-class").value;
var createRoomName = plainText.replace(/(<([^>]+)>)/gi, "");
createRoomName = createRoomName.replace(/ +/g, "");
createRoomName = createRoomName.trim();
if(createRoomName.length == 0){
alert("empty");
} else if(createRoomName.length < 5){
alert("Room name must be equal or longer than 5 characters");
} else if(!createRoomName.length == 0)
{
getCreatedRoomName(createRoomName);
window.location = createRoomName;
}
}
});
}
createRoom();
function getCreatedRoomName(x){
return x;
}
What it does is first checks if input field is not empty and if not smaller than 5 characters. If everything is fine then we pass that value to a function and then redirect to that created name url. Look below.
getCreatedRoomName(createRoomName);
window.location = createRoomName;
And we return value (return x)
function getCreatedRoomName(x){
return x;
}
How can I retrieve that returned value in nodejs? I tried modules it doesn't work for some reason.

Having a main function call smaller functions?

I've got three separate functions for my javascript:
<script>
function validateName() {
var x = document.forms["booking_form"]["firstname"].value;
if (x == null || x == ""){
alert("First name is not filled");
return false;
}
var y = document.forms["booking_form"]["lastname"].value;
if (y == null || y == ""){
alert("Last name is not filled");
return false;
}
//var z =
}
function validateAge(){
if(document.booking_form.age.value < 18){
alert("You must be at least 18 years of age");
return false;}
else{
return true;}
}
function validateEmail(){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(booking_form.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
</script>
How do I call these separate functions into one main function? I'm not very good with Javascript, so I'm pretty stumped :|
If I understand correctly (let me know if I don't), it looks like you want to create a function that calls each of these individual functions and returns true only if all three validations succeed.
To do that, you'd simply use the && operator like this:
function validate() {
return validateAge() && validateName() && validateEmail();
}
This function will tell you if the age is valid AND the name is valid AND the email is valid.
For this to work, as nnnnnn pointed out, you'd have to return true in the last line of your validateName function; otherwise it would return undefined when the validation succeeds.
Just make a new function and this call others
<script>
function validateName() {
var x = document.forms["booking_form"]["firstname"].value;
if (x == null || x == ""){
alert("First name is not filled");
return false;
}
var y = document.forms["booking_form"]["lastname"].value;
if (y == null || y == ""){
alert("Last name is not filled");
return false;
}
//var z =
}
function validateAge(){
if(document.booking_form.age.value < 18){
alert("You must be at least 18 years of age");
return false;}
else{
return true;}
}
function validateEmail(){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(booking_form.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
function globalFunction() {
validateAge();
validateName();
validateEmail();
}
</script>
In this example, you need call a "globalFunction();"
Bye

Javascript: multi-tiered conditional, use of "return false" stopping later conditional checks

Return false isn't doing quite what I want it to do. I want it to prevent the form submit if any one of the conditionals passes, but I still want it to proceed down the tree of conditionals. Right now if the first conditional if ($(".item.active").length == 0) { passes, it hits the return false; and stops the later conditionals from checking.
How can I rewrite this to work better?
$('#go').click(function() {
function invalidBtn(){
$('#go').addClass('invalid');
setTimeout(function() {
$('#go').removeClass('invalid');
}, 5000)
}
$('.error').remove();
$('.invalid').removeClass('invalid');
if ($(".item.active").length == 0) {
$(".item:first-of-type").before('<h5 class="error">Select a shirt type</h5>');
invalidBtn();
return false;
} else {
if ( $(".item.active .size-select .active").length == 0) {
$('.item.active .size-select').before("<div class='error'>Select a size</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
if ($(".item.active .gender-select").length > 0 ) {
if ( $(".item.active .gender-select .active").length == 0 ){
$('.item.active .gender-select').before("<div class='error'>Select a gender</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
}
}
if ( !$('#fn-field').val() ) {
$('#fn-field').before("<div class='error'>Enter your first name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
if ( !$('#ln-field').val() ) {
$('#ln-field').before("<div class='error'>Enter your last name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
});
Thanks so much
Simply replace all of your return false to change a boolean, and return the boolean, like this:
$('#go').click(function() {
function invalidBtn(){
$('#go').addClass('invalid');
setTimeout(function() {
$('#go').removeClass('invalid');
}, 5000)
}
var retVal = true;
$('.error').remove();
$('.invalid').removeClass('invalid');
if ($(".item.active").length == 0) {
$(".item:first-of-type").before('<h5 class="error">Select a shirt type</h5>');
invalidBtn();
retVal = false;
} else {
if ( $(".item.active .size-select .active").length == 0) {
$('.item.active .size-select').before("<div class='error'>Select a size</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
if ($(".item.active .gender-select").length > 0 ) {
if ( $(".item.active .gender-select .active").length == 0 ){
$('.item.active .gender-select').before("<div class='error'>Select a gender</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
}
}
if ( !$('#fn-field').val() ) {
$('#fn-field').before("<div class='error'>Enter your first name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
if ( !$('#ln-field').val() ) {
$('#ln-field').before("<div class='error'>Enter your last name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
return retVal;
});
Return false isn't doing quite what I want it to do. I want it to prevent the form submit if any one of the conditionals passes, but I still want it to proceed down the tree of conditionals. Right now if the first conditional if ($(".item.active").length == 0) { passes, it hits the return false; and stops the later conditionals from checking.
Right, because return exits the function.
If you want to keep going through the code following it, don't use return, set a variable you return at the end. E.g.:
var valid = true;
if (someInvalidCondition) {
// ...do anyting condition-specific...
valid = false;
}
if (someOtherInvalidCondition) {
// ...do anyting condition-specific...
valid = false;
}
// Rinse, repeat
// Done
return valid;
Or I usually like to return a count of the errors. Or a list (array) of the errors. Etc.

Javascript test() method syntax error?

I'm attempting to convert (what I've found to be) the best email validation function (located here: http://www.linuxjournal.com/article/9585?page=0,3) from php to javascript. Regardless of the fact that "you shouldn't validate with javascript because javascript can be disabled". Obviously I can't leave in the checkdnsrr() portion of the function, but everything else should be doable with javascript.
So far the function works as expected up until this line:else if(/\.\./.test(domain)) {
I know it's pretty useless without context, so the full function is below. What's also weird is that it gives a "pass" to a line with the exact same regex pattern:else if(/\.\./.test(local)) { which is used a few lines before it. Strange.
function validEmail(email) {
var isValid = true;
var atIndex = email.indexOf("#");
var ending = email.length - 1;
if(typeof(atIndex) == "boolean" && !atIndex) {
isValid = false;
}
else {
var domain = email.substr(atIndex+1);
var local = email.substr(0, atIndex);
var localLen = local.length;
var domainLen = domain.length;
if(localLen < 1 || localLen > 64) {
// local part length exceeded
isValid = false;
}
else if(domainLen < 1 || domainLen > 255) {
// domain part length exceeded
isValid = false;
}
else if(local[0] == '.' || local[localLen-1] == '.') {
// local part starts or ends with '.'
isValid = false;
}
else if(/\.\./.test(local)) {
// local part has two consecutive dots
isValid = false;
}
else if(/^[A-Za-z0-9\\-\\.]+$/.test(domain) == false)
// character not valid in domain part
isValid = false;
}
else if(/\.\./.test(domain)) {
// domain part has two consecutive dots
isValid = false;
}
else if(/^(\\\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/.test(local.replace("\\\\",""))) {
// character not valid in local part unless
// local part is quoted
if(/^"(\\\\"|[^"])+"$/.test(local.replace("\\\\",""))) {
isValid = false;
}
}
}
return isValid;
}
You missed a { in the previous if.
Therefore, that else has no if connected to it.

Javascript How To Evaluate On Number or Specific String

I need to evaluate a form submission to either be
"TBD" or a number > 0 . Is there a way to do that that I'm not seeing.. here is what I have so far:
<script language="Javascript">
function validateForm(){
//Declare Variables
var aa=document.forms["form"]["irnumber"].value;
if (aa =='TBD'){
return true;
}else if (parseInt(aa) < 1 || aa==null || aa=="") {
alert("IR Must Be A Number Or \"TBD\" ");
return false;
}
</script>
Any help is very much appreciated.
if (parseInt(aa) > 0 || aa === "TBD") {
return true;
} else {
alert("IR Must Be A Number Or \"TBD\" ");
return false;
}
or
if (/^((TBD)|(0*[1-9]+[0-9]*))$/i.test(aa)) {
return true;
} else {
alert("IR Must Be A Number Or \"TBD\" ");
return false;
}

Categories

Resources