Overriding a global variable in Javascript - javascript

$(document).ready(function(){
var min="1.2.2";
$.validator.addMethod('xyz', function(value, element, param) {
alert(min);
min=minAorB();// I want to call a function which will return the minimum among A and B.
alert(min);
return (validateAnmcComp(value,param));
}, "Please enter a value less than or equal to "+min);
})(jQuery);
I want the message to be displayed as "Please enter a value less than or equal to 1.4.5"

Would this help?
$(document).ready(function($) {
function createMinValidator(min) {
return function(value, element, param) {
// use min as required
return (validateAnmcComp(value, param));
};
}
var min = "1.4.5";
var msg = "Please enter a value less than or equal to " + min;
$.validator.addMethod('xyz', createMinValidator(min), msg);
});

Related

html - use onsubmit and action together

I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}
If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.

Messed up my JavaScript return statements

I have a function defined like this:
var getPhoneNumber = function (list, phoneType) {
if (_.isEmpty(list)) {
return "Not Entered"
};
_.each(list, function(phoneNo){
if (phoneNo.name === phoneType) {
return phoneNo.value;
};
});
return "Not Entered";
}
list is an Array, while phoneType is a String. The problem is the function always returns the value Not Entered even if the list is not empty and has a phoneNo.name equal to phoneType. If I add a console.log in the if it shows that the condition is true and prints the console.log message but still returns Not Entered
return phoneNo.value; doesn't correspond to the function getPhoneNumber, but to the function passes as callback at _.each.
You should try something like this instead:
var getPhoneNumber = function (list, phoneType) {
var value = null;
_.each(list, function(phoneNo){
if (phoneNo.name === phoneType) {
value = phoneNo.value;
}
});
if(value !== null)
return value;
else
return "Not Entered";
}

How to keep cents in a Angular math function

I have a math function that adds two input fields and puts the value in a third. I also have a filter that adds the cents to the input. you will see in the plunkr that the filter is not being applied to the Revised Contract. Original Contract + Total CO = Revised Contract.
plunkr
$scope.$watch('currentItem.JobOriginalContract -- currentItem.JobTotalCO', function (value) {
if (!$scope.currentItem) $scope.currentItem = {};
$scope.currentItem.JobRevisedContract = value;
});
$scope.$watch('currentItem.JobRevisedContract * .85 ', function (value) {
if (!$scope.currentItem) $scope.currentItem = {};
$scope.currentItem.JobOriginalBudget = value;
});
$parsers run only when you change the ngmodel value from the DOM (ex:- entering in the input box). When you programatically change the value (as you do for JobRevisedContract and JobOriginalBudget) it is $formatters that run. So you would need to format in formatters.
Example:-
ctrl.$formatters.unshift(function (a) {
return getFormattedValue(ctrl.$modelValue);
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+]/g, '');
elem.val(getFormattedValue(plainNumber));
return plainNumber;
});
function getFormattedValue(value){
return $filter(attrs.format)(value/100,2);
}
Demo

set variable value to jquery message + jquery.validate

How to get value of var total in message,
and also i tried declare inside function but it gives undefined variable
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
var fund_old = $("#current_fund").val();
var fund_new = $("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if (parseFloat(fund_new) <= parseFloat(total)) {
return true;
} else {
return false;
}
return true;
}, 'sry sktiman' + total + 'is remaining value');
In result i am getting blank value of total
According to the documentation for jQuery.validator.addMethod() you can use jQuery.validator.format() which generates a function that receives the arguments to the validation method and returns a string message, so creating a function that ignores any arguments and returns a string should work:
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
var fund_old = $("#current_fund").val();
var fund_new = $("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if (parseFloat(fund_new) <= parseFloat(total)) {
return true;
} else {
return false;
}
return true;
}, function() {return 'sry sktiman' + total + 'is remaining value'});
EDIT
The fiddle for this solution can be found here (thanks to Sparky for providing the code).
The optional parameters can be used inside the message.
The third argument, the optional parameters, (you call it arg) can be represented within your code as arg[0], arg[1], etc.
Then the corresponding values can be used in your message as {0}, {1}, etc.
Do your calculation external to .addMethod() and pass the value in using the arg argument.
$.validator.addMethod("valueNotEquals", function(value, element, arg){
var fund_old= $("#current_fund").val();
var fund_new =$("#new_fund").val();
// do this calculation where the rule is declared. See 'validate()'
//total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if(parseFloat(fund_new) <= parseFloat(total)){
return true;
} else {
return false;
}
return true;
},'sry sktiman {0} is remaining value');
Since you didn't show your .validate() or the HTML markup, maybe something like this...
$('#myform').validate({
rules: {
fund_old: {
// your rules
},
fund_new: {
valueNotEquals: function() {
return ($parseFloat(9999999999.999999) - parseFloat($("#current_fund").val()));
}
}
}
});
Crude demo: http://jsfiddle.net/eZm7x/
Just add this line function() {return 'sry sktiman' + total + 'is remaining value'} as your second argument, you can easily use this variable
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
//Your default code here
}, function() {return 'sry sktiman' + total + 'is remaining value'});
Try,
var total = '';
$.validator.addMethod("valueNotEquals", function(value, element, arg){
var fund_old= $("#current_fund").val();
var fund_new =$("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if(parseFloat(fund_new) <= parseFloat(total)){
return true;
}else{
return false;
}
return true;
},'sry sktiman'+ (parseFloat(9999999999.999999) - parseFloat($("#current_fund").val())) + 'is remaining value');
In addMethod Documentation says: "Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message."
So, you are adding a custom validation function to plugin, and NOT executing that function.
Try to set a field with your custom validation and fill that field to run your custom function. Just AFTER that check total var value.

I keep getting stuck in an infinite loop when testing a string using a function in a for loop

When I test a string using the inputName function, I get stuck in an infinite loop that keeps displaying the alert() functions in the browser. I'm not sure the logic behind why it's happening. Note this is for a school assignment and I'm required to use a for loop and a function with parameters to test inputted data called employeeName. The function tests to see if the data is null, empty or a number before returning a value.
<html>
<head>
<script type="text/javascript">
function inputName(name)
{
var flag;
do
{
flag = false;
if (name == null)
{
alert("You have hit the 'Cancel' button!");
return name;
flag = false;
}
if (name == "")
{
alert("You tried entering no name!");
flag = true;
}
else if (!isNaN(name))
{
alert("You tried entering a number!");
flag = true;
}
else if (name.length < 2)
{
alert("You tried entering a name less than 2 characters!");
flag = true;
}
} while (flag);
return name;
}
</script>
</head>
<body>
<script type="text/javascript">
// DECLARATIONS
var numEmployees;
var employeeName;
var testName;
// INPUT
numEmployees = prompt("Enter the number of employees");
// PROCESSING
for (var index = 1; index <= numEmployees; index++)
{
employeeName = prompt("Enter a name.");
testName = inputName(employeeName);
}
// OUTPUT
</script>
</body>
</html>
Because you are not prompting for a new name inside of the loop, the name never changes so you keep testing the same string over and over again.
You're not using a for loop; that's a do ... while loop.
The problem is that you set "flag" to true, but nothing happens to set it to false before you loop around and set it to true again. If the function starts off with the "name" being empty, a number, or a single-character string, that loop will just go on and on.
You need to prompt the user to correct the name.
var getName = function() {
var name;
do {
name = prompt("Enter a name.");
} while(!validateName(name));
return name;
};
var validateName = function(name) {
if (name == null) {
alert("You have hit the 'Cancel' button!");
return true;
}
if (name == "") {
alert("You tried entering no name!");
return false;
}
else if (!isNaN(name)) {
alert("You tried entering a number!");
return false;
}
else if (name.length < 2) {
alert("You tried entering a name less than 2 characters!");
return false;
}
return true;
};

Categories