i'm new to programming , i don't understand this line if(!validateform(siteName,siteURL)) ,what happens if function return false , will it enter the if condition ???
if(!validateform(siteName,siteURL))
return false;
// Validate Form
function validateForm(siteName, siteUrl){
if(!siteName || !siteUrl){
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if(!siteUrl.match(regex)){
alert('Please use a valid URL');
return false;
}
return true;
}
If the function returns false it will enter the if condition, but if the function returns true it won't enter the if condition. This is because you are using the not operator (!).
The not operator simply makes a boolean true value into a false value and a false to a true value.
Firstly there is an error in the line you want to know about when you're calling a function remember it is case-sensitive. Your function is defined as validateForm but you are calling it with validateform.
That aside the below snippet is an attempt to explain what the function does during runtime.
in the below snippet
if(!validateForm(siteName,siteURL))
what this line does is it calls the function validateform() and passes the arguments siteName and siteURL . The function performs certain validations on the parameters and depending on the outcome of the validating statements(commented below) it returns true or false. The condition in the if statement !validateForm(siteName,siteURL) checks to see if the output of the function is false (ie return false;). If it is false it will execute the if statement(remember this depends on the parameters passed). You can see the examples in the snippet to see when the statement returns true/false.
function checkURL(siteName, siteUrl) {
if (!validateForm(siteName, siteUrl)) {
console.log("invalid name " + siteName);
console.log("invalid URL " + siteUrl);
return false;
} else {
console.log("Site name is valid " + siteName);
console.log("Site URL is valid " + siteUrl);
}
}
// Validate Form
function validateForm(siteName, siteUrl) {
if (!siteName || !siteUrl) { //validating statement 1
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (!siteUrl.match(regex)) { //validating statement 2
alert('Please use a valid URL');
return false;
}
return true;
}
console.log("URL and name valid");
checkURL("stackoverflow","https://www.stackoverflow.com");
console.log("URL invalid")
checkURL("stackoverflow","stackoverflow");
console.log("Name not defined");
checkURL(undefined,"https://www.stackoverflow.com");
console.log("URL not defined");
checkURL("stackoverflow",undefined);
Related
function ClientContactCheck(){
var clientcontact = $("#client_contact_id").val();
if(clientcontact.length != ""){
if(!isNaN(clientcontact)){
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
}
}else{
$("#client_contact_id").css('border-color', "red");
}
return false;
}
i am using this function to validation phone number , my intention is simple just not be empty and must be number.
but if put !isNaN and my input was 123-456-789 , it wont valid cause the - was not a number, how to i make my function bypass the - ?
so if the input value had - it will pass thought.
thank
You can use :
str.replace("-", "");
and then check your input if it is a number only.
Edit:
var res = str.replace(/\-/g,'');
You can check it with a regular expression:
var clientcontact = $("#client_contact_id").val();
if (/^[0-9\-]+$/.test(clientcontact)) {
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
} else {
$("#client_contact_id").css('border-color', "red");
return false;
}
This will allow '-', '--', '---' too. If that is not desired, you can do one more check: ... && !/^-*$/.test(clientcontact)
You can do something like this to validate the phone number.
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
More at http://www.w3resource.com/javascript/form/phone-no-validation.php
I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a HTTPRequest that returns a value. I'm capturing such value with a callback function.
The code executes and alert if the username is duplicate in the DB. However the "return false" is not working and the form is submitted (saveNewUser) with the duplicated username anyway. All the examples I've seen so far just stop at the callback with an alert just like I have in my code. So how do I accomplish that the return false stop the execution like in the other cases: first, last name and password checks?
Thank you so much.
function checkUsername(callbackUsername){
var username = document.getElementById('username_id').value;
var ajaxRequest = getXMLHttp();
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var response = trim(ajaxRequest.responseText);
callbackUsername(response);
}
};
var url = "../admin/check_unique_username.php";
var parameters = "username="+username;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(parameters);
}
function checkNewUserForm(){
if(document.getElementById('first_name_id').value === ""){
alert("First Name cannot be blank!");
document.getElementById('first_name_id').focus();
return false;
}
if(document.getElementById('last_name_id').value === ""){
alert("Last Name cannot be blank!");
document.getElementById('last_name_id').focus();
return false;
}
checkUsername(function(result) {
if(result > 0){
alert("ERROR: Username already exist. Please select a different username!!");
document.getElementById('username_id').focus();
return false;
}
});
re = /[0-9]/;
if(!re.test(document.getElementById('password_id').value)) {
alert("Error: password must contain at least one number (0-9)!");
document.getElementById('password_id').focus();
return false;
}
saveNewUser(first_name,last_name,username,password);
}
By return false you will only return from the callback function. You have to return from the checkNewUserForm() function to stop saving the new user. For this to happen, you can use a boolean variable hasDuplicateUsername to check whether a duplicate username entry is there, so that you can make it to true, inside the callback. And before saveNewUser() you should check whether it is false.
function checkNewUserForm(){
var hasDuplicateUsername = false;
if(document.getElementById('first_name_id').value === ""){
alert("First Name cannot be blank!");
document.getElementById('first_name_id').focus();
return false;
}
if(document.getElementById('last_name_id').value === ""){
alert("Last Name cannot be blank!");
document.getElementById('last_name_id').focus();
return false;
}
checkUsername(function(result) {
if(result > 0){
alert("ERROR: Username already exist. Please select a different username!!");
document.getElementById('username_id').focus();
hasDuplicateUsername = true;
}
});
re = /[0-9]/;
if(!re.test(document.getElementById('password_id').value)) {
alert("Error: password must contain at least one number (0-9)!");
document.getElementById('password_id').focus();
return false;
}
if(!hasDuplicateUsername) {
saveNewUser(first_name,last_name,username,password);
}
}
I'm doing a regex check on a string within a function:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/,
matches = regex.exec(listOfZipCodes);
if (regex.exec(listOfZipCodes) === null) {
console.log('validation failed');
return false;
} else {
console.log('validation passed');
return true;
}
}
The regex is correctly detecting a valid/invalid list of zip codes.
I'm calling the function with this:
console.log('zip code: ' + listOfZipCodes);
if (ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
The problem is that the above if/else goes to the else clause, when the console output within the validation function shows "validation failed". So I must not be calling that function right.
What's the correct way to do what I'm trying to do?
Your function could be greatly simplified to:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
if (regex.test(listOfZipCodes)) {
console.log('validation passed');
return true;
} else {
console.log('validation failed');
return false;
}
}
...or:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
return regex.test(listOfZipCodes);
}
...or even just:
function ValidateZipCodeString(listOfZipCodes) {
return /^([, ]*\d{5})+[, ]*$/.test(listOfZipCodes);
}
...but the real issue (as Teemu points out) is not in your function, but in the use of it. Your function answers the question, "Is this a valid zip code string?", but your use of it is saying, "Say this is invalid if my function says it is."
Actually your validation function doesn't return true when validation fails. You just check the value incorrectly, it should be:
if (!ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
Others correctly pointed out that you just had your tests in the wrong order. However, and more importantly, your regex is incorrect, as it will for example return true for "1234567890".
Here is a suggestion:
function ValidateZipCodeString(listOfZipCodes) {
return /^\d{5}(\s*,\s*\d{5})*$/.test(listOfZipCodes);
}
I have variable deleteboxvalue
var deleteboxvalue = "111111111111111";
if(deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected."); return true;
}
I want to check if 0 is not exist in this I want to return false and alert as "You can't delete all Contact Number." but in both cases if 0 exist in variable in that case also its returning false and giving me alert as "You can't delete all Contact Number."
I want to check if 0 is not exist in this I want to return false
If that's the case then you've got your logic reversed. You are currently returning false if 0 is in the string (i.e. it is found at an index greater than or equal to 0). If you want to return false when 0 is not found in the string, you can do this:
if(deleteboxvalue.indexOf('0') == -1) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected.");
return true;
}
However, I may have completely misunderstood what you're trying to do...
Create a function in JavaScript such as:
function CheckContacts() {
var deleteboxvalue = "111111111111111";
if (deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
} else {
alert("All Zeros are not selected."); return true;
}
}
and
On body onload call that JavaScript method:
<body onload="CheckContacts()">