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());"
Related
Here is a link to my JS fiddle: https://jsfiddle.net/apasric4/v1qkmgyu/1/
function inputCheck(input) {
if (input.name==="email") {
console.log("email")
return isValidEmail
} else if (input.name==="password") {
return isValidPassword
console.log("pass")
} else if (input.name==="userName") {
return isValidUserName
console.log("user")
}
}
function isValidEmail (email) {
return /^[^#]+[#][^#.]+\.[a-z]+$/.test(email)
}
function isValidPassword(pass) {
return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(pass)
}
function isValidUserName(user) {
return /^[a-zA-Z0-9]+([_ -]?[a-zA-Z0-9])*$/.test(user)
}
function validation(e) {
e.preventDefault()
inputs.forEach(input=> createListener(inputCheck(input)))
}
function createListener(validator) {
return (e)=> {
const inputValue=e.target.value;
const valid=validator(inputValue)
console.log(valid)
}
}
I'm trying to create form validation using closures. I am trying to make my code as efficient as possible.
I want to loop over each input element (without selecting each individually), and apply an event listener to each one. The inputCheck function would return a validator function depending on the name attribute of each input, and the createListener function takes the value returned by inputCheck, which would be a specific type of validator, and then for testing purposes, console.log true or false.
So far, the only if branch that works in the inputCheck function is the first one associated with name attribute email. The other if branches won't work if I type values into other input elements and submit the form.
Can anyone tell me where I'm going wrong and how to improve my code?
I'm new to closures so I understand that this issue might seem relatively simple to most of you.
I can observe two things:
First, just like #VLAZ pointed out, two console.log in inputCheck are actually not executed since they are placed after return.
Second, createListener and validation are not quite right. createListener returns a function with one argument. validation forEach doesn't log anything because createListener returns a function, no function execution here.
There is another problem with the argument e of createListener. It seems like you treat it as an event, but based on your implementation, there is only one event, that is form submit event. So, I'd suggest to modify these two functions a little bit:
function validation(e) {
e.preventDefault()
inputs.forEach(input=> createListener(inputCheck(input))(input))
}
function createListener(validator) {
return (e)=> {
const inputValue=e.value;
const valid=validator(inputValue)
console.log(valid)
}
}
Then, the console prints out true or false based on the input value of each input field.
Please check whether the output is your intension or not https://jsfiddle.net/jqgbefhw/
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
}
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() != "";
}
}
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.
Is it possible to compact the function below so there is no variable created?
var flag=true;
//...
my.flagValue=function(){
var f=flag;
flag=false;
return(f);
};
Basically, to set and return (the previous) value at the same time.
Well, normally there's no way to return something before setting it. But in this specific case, you can use some magic to pull it off. Though your original code is far more readable and maintainable:
my.flagValue = function () {
return (flag && !(flag = false));
};
If flag is true, then it will perform like this:
return (true && !(flag = false)); //!(flag = false) is true, so true is returned.
If flag is false, then it will perform like this:
return (false && !(flag = false)); //obviously returns false.
Though, I really do encourage you not to do this. It's obscure and requires a bit of logic parsing to sort out. I just wanted to demonstrate that it's possible to do what you're looking to do in this specific case.
If you are just flipping the value of flag between true and false then this might work for you:
my.flagValue=function(){
return !(flag = newValue);
};
This will set flag to newValue and return opposite value from the function.
You can try this as well, If I understood the question correctly :)
my.flagValue=function(){
return flag ? !flag : flag ;
};