Validation for either of the fields are non-empty - javascript

Suppose I have two text fields and I need to validate for either of the fields are non-empty.
I have tried like
"vImage": {
"myfunction_valid": function(){
if(('#vimg1').val()) return true;
else if($('#vimg2').val()) return true;
else return false;
}
}
But it is not working. Can anyone suggest me the better way?

Presumably the code shown is part of an object literal, and there could be other problems in the code you haven't shown, but in what you have shown you've got a syntax error on the line with the if:
if(('#vimg1').val()) return true;
Should be:
if($('#vimg1').val()) return true;
For further help you will need to show us more of your code. How do you call that function? What is the rest of the object that vImage belongs to?
"Can anyone suggest me the better way"
Well you could simplify the function to this:
"vImage": {
"myfunction_valid": function(){
return $('#vimg1').val() != "" || $('#vimg2').val() != "";
}
}

Related

Javascript && operator logic

I'm developing a controller in angular. For some reason there is an If statement that is giving me a issue, yes an if statement.
The code is the following:
$scope.new = function(logoFile) {
if($scope.comprobarCampoDesc() && $scope.comprobarCampoFecha() && $scope.comprobarCampoName() )
{
//program logic
}
Also there is the other pieces of code:
$scope.comprobarCampoName = function(e) {
//program logic
return bol;
};
$scope.comprobarCampoDesc = function(e) {
//program logic
return bol;
};
$scope.comprobarCampoFecha = function(e) {
//program logic
return bol;
};
Ok, For any reason that I'm not able to identify, the if statement only checks 2 of 3 methods, depending of the order. In this concrete case it is ignoring "$scope.comprobarCampoName" but if I change the order other method is witch doesn't work.
Thanks for the help.
Greetings.
In your case, if one of the conditions is equal to false, the if statement stops and does not iterate further.
If you really need to execute each of those, I recommend you to do the following :
var first = $scope.comprobarCampoDesc();
var second = $scope.comprobarCampoName();
var third = $scope.comprobarCampoFecha();
if (first && second && third){
// execute
}

How to check in angularjs if ng-model has a value of string or a number?

I have my java script in angular checking if the value of text field is undefined or empty, it is fine and working,
$scope.checkNumber = function(user_answer){
if(user_answer == undefined){
return false;
}
}
But my next step is how I can make a function to identify if the value has a string or a number and return a boolean. I don't know the right syntax for angular java script, can anyone help me to solve my problem?
You can do this the angular way, using the angular helper functions:
$scope.checkNumber = function(user_answer){
if(angular.isUndefined(user_answer)){
return false;
}
if(angular.isString(user_answer)) {
//return boolean
}
if(angular.isNumber(user_answer)) {
//return boolean
}
}
Try like this
function check(text){
return typeof text ==="number";
}

javascript variable scope - how can i work around this?

I have an input field, where a user can enter an INPUTVALUE, this INPUTVALUE gets checked for correctness against a reg-ex, then sent off to a php file, which will do calculations with it, and return either 0 (meaning the INPUTVALUE was not valid) or a RETURNVALUE. This RETURNVALUE should be displayed in an element on the website with the id #VALUEINFO. Also I would like this RETURNVALUE returned by my function get_value_by_input(). In order to check what was returned, I am displaying an alert first.
(A practical application for this could be for example a coupon code on an order... put in your coupon code, we check it in the database, it returns the value of the coupon or 0 if it was not a valid coupon code.)
My problem is, I must be messing up something with the variable scope in Javascript, because eventhough my #VALUEINFO displays the correct RETURNVALUE, the alert will always say no returnvalue specified.
function get_value_by_input()
{
var returnvalue;
var valueinfo = $('#valueinfo');
valueinfo.text('');
var inputvalue = $("input[name='inputvalue']").val();
var correctinput = /^[a-zA-Z]*$/i;
if( inputvalue.length > 0 && correctinput.test(inputvalue))
{
$.post('ajax/valuecheck.php', {inputvalue_test: inputvalue}, function(is_valid){
if(is_valid == 0)
{
valueinfo.text('Sorry, this input is not working...');
returnvalue = 0;
}
if(is_valid != 0)
{
valueinfo.text('the returned value for your input is '+is_valid);
returnvalue = is_valid;
}
});
}
else
{
if(inputvalue)
{
valueinfo.text('Invalid input.');
returnvalue = 0;
}
}
if(returnvalue)
{
alert('the value for this input was was '+returnvalue);
return returnvalue;
}
else
{
alert('no returnvalue specified.');
return 0;
}
}
Again:
Why does this code ALWAYS alert 'no returnvalue specified' eventhough #VALUEINFO gives me the correct returnvalue?
I assume this has to do with the if block, I read that javascript will not ignore the setting of any variables within if blocks, even if the condition is not fulfilled... But how else could I pass the value to #valueinfo and return it at the same time?
Any help or suggestions would be greatly appreciated! :-)
EDIT:
Well, yes it has nothing to do with variable scope, but it's about Asynchronus-jax.
I ended up restructuring my code... get_value_by_input() is now more of a process_input() function. First the INPUTVALUE is checked for correctness, and only if there were no errors $.post(... is called. The value returned by the php file is then used immediately within the callback function, rather then to be returned and then used from another function... Unfortunately I couldn't get my brain wrapped around working with .done() or something similar, guess I've been working too long on this today already... -.- Maybe next time. It works for now :)
As mentioned in the comments, you need to handle the return value in a callback (since you're dealing with an asynchronous call).
This might give you a better understanding on how to solve the problem:
function getReturnValue(inputvalue, callback){
$.post('ajax/valuecheck.php', { 'inputvalue_test': inputvalue}, callback);
}
var inputvalue = $("input[name='inputvalue']").val();
getReturnValue(inputvalue, function(is_valid){
//handle is_valid here
//it's the data returned from the ajax call
});
There are a lot of similar threads.

Define a function that will be implemented by the user

I have the following example code
var object = {
userDefinedFunction : function(){
//no implementation, this will be defined by the user
}
}
What i want to achieve is the user giving his own implementation of it:
object.userDefinedFunction = function(){
alert("just testing");
}
I tested this and works as i expected, what i want to know is:
is this the javascript way of solving this kind of problem?
let's say that it's mandatory that userDefinedFunction is implemented, how do i make sure of this? I could rely on something like the following, checking for implemented, but i'm learning javascript so i want to know how to leverage the language:
userDefinedFunction : function(){
implemented = false;
}
Thank you.
I don't know if this is the way to go, but if your object has to be initialized somehow by the user, you can test in this function, whether userDefinedFunction is defined and throw an exception if not.
One idea that feels to be a cleaner implementation, is to let the user provide some kind of configuration object that defines the functions, something like:
yourObject.initialize({
userDefinedFunction: function() {}
});
You could throw an error in the default implementation:
var object = {
userDefinedFunction : function(){
throw "userDefinedFunction must be implemented";
}
}
or show an alert box, depending on your application.
var object = {
userDefinedFunction : undefined,
anotoherDefinedFunc : undefined,
/* ... */
hasUserImplementedInterfaces : function() {
if (typeof object.userDefinedFunction !== 'function') return false;
if (typeof object.anotoherDefinedFunc !== 'function') return false;
/* ... */
return true;
}
};
console.log(object.hasUserImplementedInterfaces());
hasUserImplementedInterfaces() function checks for user function implementations so you can execute as first check using that object.

Javascript - multiple client-side validations on same event

I am performing two validations on the client side on the samve event.
I have defined my validations as shown below
btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();"
Pseudo code for
prepareSave():
{
if (bPendingchanges)
{
return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first')
}
else
{return true}
}
Pseudo code for
prepareSearch():
{
if (bNoSearchText)
{
alert('Please specify search criteria before proceeding')
return false;
}
else
{return true;}
}
When bPendingchanges=false, I never get the second validation running.
Anyone who can quickly spot what I have overlooked here? Please?
return, as the name implies, returns control back to whatever called the code in question. Therefore, anything that's after a return statement
return prepareSave(); return prepareSearch();
// ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part
never executes. Try return (prepareSave() && prepareSearch());
Your second return statement will never be reached. Execution stops after javascript:return prepareSave().
Looks like you want to return true if both functions return true - therefore, do:
btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch();
That's because the return prevents the second validation from running. Try this
btnSearch.Attributes["OnClick"] = "javascript:return prepareSave() && prepareSearch();"
"javascript:return prepareSave(); return prepareSearch();"
1) You shouldn't have the "javascript:"
2) return prepareSearch(); will never be executed, because "return prepareSave(); exits your event handler
Try "return (prepareSave() && prepareSearch());"

Categories

Resources