New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need to validate a part of my form which is the postcode based on Malaysia's postcode which is a 5 digit numeric postcode. How to validate a value enter by user which has exactly 5 numbers only no more and no less? Thanks in advance!
Here's my part of the code:
HTML:
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />
Javascript:
function chkPostcode () {
var postcode = document.getElementById("postcode").value;
var pattern = /^[0-9]+$/; //check only alpha characters or space
var postcodeOK = true;
if ((postcode.length < 5 && postcode.length > 5)){ //same as owner==""
gErrorMsg = gErrorMsg + "Please enter postcode.\n"
postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(postcode)){
gErrorMsg = gErrorMsg + "Postcode must only contain numbers.\n"
postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
}
}
//if (!nameOk){
// document.getElementById("owner").style.borderColor = "red";
//
return postcodeOK;
}
This is a much shorter code for what you're trying to accomplish.
document.getElementById("postcode").addEventListener("input", function(e) {
if ( /^\d{5}$/.test(e.target.value)){
console.log("valid");
return;
}
console.log("invalid");
})
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />
Your JavaScript is unnecessarily complicated. Here's a sure (and much better) way (except for all the ifs) to do this (the button and the check function are just for demo purposes):
function chkPostcode() {
var postcode = document.getElementById("postcode").value;
if(postcode.length !== 5)
{
return false;
}
else {
if(!isNaN(parseInt(postcode.charAt(0)))) {
if(!isNaN(parseInt(postcode.charAt(1)))) {
if(!isNaN(parseInt(postcode.charAt(2)))) {
if(!isNaN(parseInt(postcode.charAt(3)))) {
if(!isNaN(parseInt(postcode.charAt(4)))) {
return true;
}
}
}
}
}
}
return false;
}
function check() {
if(chkPostcode()) alert("Valid!");
else alert("Not a postcode");
}
<input type="text" id="postcode" />
<button onclick="check()">Check</button>
Just keep in mind, although client side (JavaScript) validation scripts are helpful, it's easy to defeat client-side JavaScript. Make sure you make some validation on the server-side as well, where the client can't tamper with the code as easily.
I am trying to use the ErrorFoundFlag approach to Show an error message for all fields that are in error at once.
I have tried:
function processInfo() {
var errorFoundFlag = "N"; //Initialize variable to 'N'
firstName = $("firstname").value;
lastName = $("lastname").value;
numPets = $("numpets").value;
var message = "";
if (firstName >= 0) {
firstName = firstname.length;
msg += "Please enter first name";
errorFoundFlag = "Y";
}
if (lastName >= 0) {
lastName = lastname.length;
msg += "Please enter last name";
errorFoundFlag = "Y";
}
if (numPets >= 0) {
numPets = numpets.length;
msg += "Please enter the number of pets you have";
errorFoundFlag = "Y";
}
}
<p>
Enter First Name: <input type="text" id="firstname" />
<span id="firstname_error"></span>
</p>
<p>
Enter Last Name: <input type="text" id="lastname" />
<span id="lastname_error"></span>
</p>
<p>
How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1" />
<span id="numpets_error"></span>
</p>
I need the error message to appear next to the input boxes when no text is input. And when text is input, the error message should go away but it's not working for me.
for example:
if the
Enter First Name: is blank... (Please Enter First Name) Would Appear
but if the name is entered the error message should go away. and if the other two are blank but the first name is entered when they click submit there would be error messages showing for the ones left blank.
There are several issues, but making the minimum number of changes to get roughly what you're asking for could look something like the following.
First, to get the value with jQuery you'll want val() (instead of value): $("#firstname").val().
Then simple references to the error spans (for example: $("#firstname_error")). These are cleared every time so the errors go away.
Then comparing the values length to 0 (note this could still be buggy, for example, an empty space would pass: " ").
Then console logging the errorFoundFlag to do as you need.
Finally, calling this method on each input change with onchange.
There are a number of improvements that can be made, but these were the minimum number of changes to get what you had working.
function processInfo() {
var errorFoundFlag = "N"; //Initialize variable to 'N'
firstName = $("#firstname").val()
lastName = $("#lastname").val();
numPets = $("#numpets").val();
firstNameError = $("#firstname_error");
lastNameError = $("#lastname_error");
numPetsError = $("#numpets_error");
firstNameError.text("")
lastNameError.text("")
numPetsError.text("")
if (firstName.length === 0) {
firstNameError.text("Please enter first name");
errorFoundFlag = "Y";
}
if (lastName.length === 0) {
lastNameError.text("Please enter last name");
errorFoundFlag = "Y";
}
if (numPets.length === 0) {
numPetsError.text("Please enter the number of pets you have");
errorFoundFlag = "Y";
}
console.log(errorFoundFlag)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Enter First Name: <input type="text" id="firstname" onchange="processInfo()" />
<span id="firstname_error"></span>
</p>
<p>
Enter Last Name: <input type="text" id="lastname" onchange="processInfo()" />
<span id="lastname_error"></span>
</p>
<p>
How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1" onchange="processInfo()" />
<span id="numpets_error"></span>
</p>
I'm a total Js noob and i'm trying to make a simple script to take values from two input tags and based on their value change a p tag. I'm probably just not using proper syntax but I can't find an answer online to how to do this.
The script is supposed to be like age verification for an r-rated movie. The first input is age and the second is whether or not the customer has an adult with them for if they are underage.
<pre>
<!DOCTYPE html>
<html>
<input type="text" id="age" value="your age">
<input type="text" id="adult" value="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
if(age.value >= 18){
oldEnough = true;
}
else{
oldEnough = false;
}
if(oldEnough == false){
if(adult.value == "y"){
result = "You are not old enough, but have an adult with you.";
}
else{
result = "You are not old enough and are unaccompanied."
}
}
else{
result = "You are old enough."
}
}
</script>
</html>
</pre>
Don't call .innerHTML on the input elements. Just set the variables to point to the elements.
When assigning the result, you need to use result.innerHTML at the time of the assignment. Assigning .innerHTML to the variable just copies the current contents of the element as a string, it doesn't make result a reference to the innerHTML property.
You should call parseInt on age, because .value is a string.
function checkAge() {
var age = document.getElementById("age");
var adult = document.getElementById("adult");
var oldEnough = false;
var result = document.getElementById("answer")
if (parseInt(age.value, 10) >= 18) {
oldEnough = true;
} else {
oldEnough = false;
}
if (oldEnough == false) {
if (adult.value == "y") {
result.innerHTML = "You are not old enough, but have an adult with you.";
} else {
result.innerHTML = "You are not old enough and are unaccompanied."
}
} else {
result.innerHTML = "You are old enough."
}
}
<input type="text" id="age" placeholder="your age">
<input type="text" id="adult" placeholder="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
The input elements can be more easily accessed if they are put in a form, and the logic can be simpler. Also, make sure you use appropriate elements and attributes, e.g. don't use value as a kind of placeholder, it should be a suitable default value (if there is one).
And don't use placeholders instead of labels, they should only be used as a hint for the kind of content required, they don't replace labels.
function checkAge(button) {
var form = button.form;
var result = document.getElementById("answer");
result.innerHTML = form.age.value >= 18? 'You are old enough.' :
form.adult.checked? 'You are not old enough, but have an adult with you.' :
'You are not old enough and are unaccompanied.';
}
<form>
<label>Age: <input type="text" name="age"></label>
<label>Adult: <input type="checkbox" name="adult"></label>
<input type="button" onclick="checkAge(this)" value="Check age">
<p id="answer"></p>
</form>
I was adding some JavaScript validation to my page and found that I couldn't find any helpful sources to tell me on how to stop numerical values and allow them on different input boxes. I am very new to JavaScript and aren't quite up to grips with it yet. I know VB has a command similar to what I am asking for: isNumeric()
Here is the code what I want to stop numerical values in:
if (document.ExamEntry.name.value=="") {
alert("You must enter your name \n");
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
alert("You must enter the subject \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
Here is the code that I want to ONLY allow numerical values in:
if (document.ExamEntry.CadNumber.value.length!== 4) {
alert("Make sure you only have 4 numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
---EDIT---
Here is what I have got so far now, it works sort of however it contstantly appears now... I was wondering if you knew anymore?
Stop Numerical values:
if (document.ExamEntry.subject.value) {
isNaN(parseInt(1));
alert("Please make sure you only have letters! \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
ONLY allow numerical values:
if (document.ExamEntry.CadNumber.value) {
isNaN(parseInt(""));
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
Look up isNaN and parseInt - they should get you started. From the JS console,
isNaN(parseInt("foo"))
true
isNaN(parseInt(12))
false
isNaN is like the opposite of your VBA isNumeric so you need to use it with parseInt on the document.ExamEntry.CadNumber.value
Use it like this:
if (isNaN(parseInt(document.ExamEntry.CadNumber.value))) {
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
To give a small example of how it could work, you could check this small snippet.
In a sense, at the moment you submit your form, it will go to the validate function, that will then check your form for the requirements.
The numbers only / text only is implied by the type (and your browser can also help), and the error message is supplied in a title.
When one field fails, the validation stops and throws the error.
Note, if you have any other elements you want to check (like selects) you would have to do some extra work still ;)
And if you want to learn more about the element types you could set, you could check it here as well
function validate(form) {
var succeeded = true,
i, len, item, itemArray, firstErrorField;
if (!form) {
succeeded = false;
} else {
itemArray = form.getElementsByTagName('input');
for (i = 0, len = itemArray.length; i < len && succeeded; i++) {
item = itemArray[i];
switch (item.type) {
case 'text':
if ((!item.value && item.required) || !isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
case 'number':
if ((!item.value && item.required) || isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
}
if (!succeeded) {
firstErrorField = item.title || item.id || item.name;
}
}
}
if (!succeeded) {
alert('please check your input!\r\n' + firstErrorField);
}
return succeeded;
}
<form onsubmit="return validate(this);">
<fieldset>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name" title="name is required" required />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" id="age" required="required" min="0" title="age is required" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</fieldset>
</form>
I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}