Hello, There are simple problem in my code, I've put myself as a user, let's assume that if the user click on the space button (in keyboard), So What is the solution.
Here my simple code:
var name = $('input#name').val(); // get the value of the input field
if(name == "" || name == " ") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Use the $.trim function to remove spaces
var name = $.trim( $('input#name').val() ); // get the value of the input field
if(name == "") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}
The .trim function in JavaScript removes leading and trailing spaces/new lines. So, if the user just spams space bar, the name.trim() will remove all leading/trailing spaces, resulting in "" and that equals "". Thus, your error code would show.
var name = $('input#name').val(); // get the value of the input field
if(name.trim() == "") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}
Related
I have an issue with my script. I have an editable field and button next to it. I tried to make a function that will start working after I will press the button and it will read data from my input field, hover it doesn't read any value from my input field and returns that the input is empty. Could you please suggest any possible solutions to it? I cannot change any input or button types to other ones. Full code: https://codesandbox.io/s/cocky-black-7mezc?file=/code.html
const trigger =
document.getElementById("poga1");
trigger.addEventListener("click", next);
function next() {
document.getElementById("input")
// default to no data
let message = "there are no data!";
const output = document.getElementById("output");
// get the value, this will be text - trim all leading and trailing spaces
const value = this.value.trim();
if (value !== "") {
// try to convert it to an integer
const numeric = parseInt(value);
// check if it's a number and if it matches what was entered
if (isNaN(numeric) || numeric != value) {
message = "not a number";
} else
if (numeric >= 1 && numeric <= 3) {
message = "not passed";
} else if (numeric >= 4 && numeric <= 10) {
message = "passed!";
} else {
message = "wrong data";
}
}
output.textContent = message;
};
<span contenteditable="true"><p id="input"></p></span>
<button id="poga1">Check!</button>
<span contenteditable="true"><p id="output">Vispirms ievadi datus!</p></span>
If you are trying to read the content of the element with an id input, then you have to change the line
const value = this.value.trim();
to
const value = input.innerText.trim();
I have a form with the ID #primarySearch. It has 3 text inputs, all of which have their own ID as follows: #ecNumber, #casNumber, #substanceName.
I have the following js. If the user enters anything in a text input in #primarySearch it runs a function called processPrimarySearch and sends the appropriate input value to it:
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
// Ignore tab key
if (e.which != 9) {
processPrimarySearch.call(this);
}
}
});
function processPrimarySearch() {
// ...
}
I've also got some other js (which is just inside document.ready) which stops the user entering anything other than numbers and dashes - but only in the #ecNumber and #casNumber fields (please note I adapted this from jQuery only allow numbers,letters and hyphens). Although this code fires if the user is entering things into these 2 fields, it also results in processPrimarySearch running irrespective of whether the user input is valid. This is because there is no connection between the code above, and the following code:
$('#ecNumber, #casNumber').keypress(function (e) {
var allowedChars = new RegExp("^[0-9\-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
// the addition, which will check the value after a keyup (triggered by Ctrl+V)
// We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
var forbiddenChars = new RegExp("[^0-9\-]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});
The result of what's happening at the moment is that if a character was entered such as "z" in #ecNumber, the validation regex code will fire and stop the character "z" appearing in the input - good. However, processPrimarySearch() will also fire because it's defined inside the .on for any input in the #primarySearch form.
My problem:
What I want to do is run the validation regex inside my .on but only if it's the #ecNumber or #casNumber fields (#substanceName must not be validated here).
I've managed to write the following which uses an array to say which field the user is entering input on. Where I'm doing the console.log is where I need the validation regex to occur
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
// Ignore tab key
if (e.which != 9) {
var arr = ["ecNumber", "casNumber"];
if ($.inArray($(this).attr('id'), arr)!== -1) {
console.log($(this).attr('id'));
}
processPrimarySearch.call(this);
}
}
});
What is the best way to do this? I'm unsure whether to move the code which does the regex into a function, and then call it (with .call?) or some other method? And are there any issues with this being asynchronous in nature?
It's all about program flow and how you want to handle it. Your problem is not really an async problem in the last way that you presented your code. Here is one solution (of many possible ones). I put some comments in the code to explain the basics.
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
// if this is not the tab key and the input contains valid characters
if (e.which != 9 && isThisValid($(this), e)) {
processPrimarySearch.call(this);
}
else {
e.preventDefault();
}
}
});
function isThisValid($elem, event) {
var ids = ["ecNumber", "casNumber"], // ids to validate, everything else is valid
result = true; // default result
// is this one of the id's to validate?
if(ids.indexOf($elem.attr('id')) !== -1) {
// do some validation
var allowedChars = new RegExp("^[0-9\-]+$"),
str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
// is it valid?
if (!allowedChars.test(str)) {
result = false;
}
}
return result;
}
function processPrimarySearch() {
// ...
}
We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;
I've learned to make the login form and I planning to validate two values ( email and password ) and use it as a condition true or false .
i have code like this
function userValid(email) {
var usr = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$\i/ ;
return usr.test(email);
};
function passValid(password) {
var passw = /^[A-Za-z]\w{7,14}$/;
return passw.test(password);
};
the code above it use to validating email and password in my form and i think if i passing a value to that function (for example passing value email to userValid() function) it will return true/false.
i plan to create validating form or login form that first check the user email & password to be valid before i submit (lets say to the server).
and i think the logic is like this :
if both values is TRUE then Login Success
if one of the values is TRUE then Login Failed
if both values is FALSE then Login Failed
else (the value must be EMPTY or NULL) then Please Insert Email and Password
and so on
my question is how to create conditional statement with ABOVE case, and of course in JAVASCRIPT :) thanks.
I don't know how you acces the email and the password, but this should work if you fill those in.
if ( userValid(email) == true && passValid(password) == true ) {
//Login succes code
}
else if ( userValid(email) == false || passValid(password) == false ){
//Login failure code
}
else {
//The "Please insert" code
}
The && operater (and) returns true only if both values are true.
The || operater (or) returns true if at least one of the values is true.
This can probably be done easier, but it should work like this.
You can add code to check if the password and the username are empty, but I don't think that's necesarry.
So what you want to do is create a function to be called when the user tries to submit your form. If this function returns false, the form will not submit. Otherwise it submits the form. You could write it like this:
var yourForm = document.getElementById("yourForm");
var yourEmail = document.getElementById("yourEmail");
var yourPassword = document.getElementById("yourPassword");
var yourWarningLabel = document.getElementById("yourWarningLabel");
yourForm.onsubmit = function() {
if (yourEmail.value == "" || yourPassword.value == "") { //Check if the fields have something in them
yourWarningLabel.innerHTML = "Please Insert Email and Password";
return false;
} else return (userValid(yourEmail.value) && passValid(yourPassword.value));
};
Where yourWarningLabel is a <p>, <label> or other text tag that you use to display the warning.
The double pipes || represent an OR operator, meaning that if the email is empty OR the password is empty we should display a warning.
The double ampersands && represent an AND operator, meaning if the email passes AND the password passes the check then we return true and submit the form, otherwise it returns false.
In addition to this you should also be checking and cleaning input on your server side or in the page that uses the input.
I’m working on a function where I’m gonna check numerous input fields with regexes. However, instead of letting it return false for each of the ”ifs” I’d like it to go through all of the conditions, and then output all of the innerHTMLs at once, from different conditions and input boxes. The text appears under each of the boxes. To give you a hint of what I'm going for.
Instead of having to input something to one box, for getting an error - correcting it, then getting a new error for the next box in the form. I'd like to see that all errors occur on the same button click. (the function trigger from a button).
The code below does not show the errors simultaneously. Is there any way to perform this without a loop? It feels like it should be, but I'm not sure how to move on.
function sum()
{
prem1 = document.formular.Uppgift1.value;
prem2 = document.formular.Uppgift2.value;
prem3 = document.formular.Uppgift3.value;
prem4 = document.formular.Uppgift4.value;
totpr = document.formular.priset.value;
varning1 = "name";
varning2 = "address";
varning3 = "phone";
varning4 = "phone number has to contain numbers";
varning5 = "e-mail";
varning6 = " - This one is not relevant to the input fields and should only show when thus are correct - ";
var re = /^[\w ]+$/;
if(!re.test(prem1)) {
document.getElementById('texterror1').innerHTML = (varning1);
form.inputfield.focus();
return false;
}
if(!re.test(prem2)) {
document.getElementById('texterror2').innerHTML = (varning2);
form.inputfield.focus();
return false;
}
if(!re.test(prem3)) {
document.getElementById('texterror3').innerHTML = (varning3);
form.inputfield.focus();
return false;
}
var re = /^(?=.*[0-9])\w{1,}$/;
if(!re.test(prem3)) {
document.getElementById('texterror4').innerHTML = (varning4);
form.inputfield.focus();
return false;
}
if(!re.test(totpr)) {
alert (varning6);
form.inputfield.focus();
return false;
}
var re = /^[\w ]+$/;
if(!re.test(prem4)) {
document.getElementById('texterror5').innerHTML = (varning5);
form.inputfield.focus();
return false;
}
else (alert ("Tack för din beställning " +prem1 + "! Här följer de uppgifter vi mottagit om dig. Adress: " +prem2 +" Tel.nr: " +prem3 +" E-post: " +prem4 +" Pris att betala: " +Discount +" kr" ));{
return true;
}
}
The code was translated on the relevant parts
Instead of returning false in each if statement, create a var to handle the error validation setting it to false in each failed if statement.
Only at the end of your function should you then return true or false by checking that var.
I would probably use a single variable failed setting it to false, only setting it to true in any one of the tests fail. But I would also use an array (an object) to store the error messages, using the ids as keys.
I would probably also store the regexes and original error messages in arrays. Using loops would be sensible though, to go through the elements and arrays.