Javascript Phone Number Validation- error message erace - javascript

Goal:
Phone number must be entered in this format, 208-111-1111; otherwise it shows the error message.
What is the best way to show the error message when the user entered in the correct format but if the user re-entered in the correct format, the error message will disappear.
JS
phoneNumber = document.getElementById("phone");
var result = phoneNumber.toString().match(/^\d{3}-\d{3}-\d{4}$/);
function validatePhone(){
if (result == null)
{
error2.innerHTML = "The number is not in a correct format";
} else
{
error2.innerHTML = " ";
};
}
HTML
<p>Phone:</p>
<input type = "text" id="phone" name="phone" onChange="validatePhone()">
<br>
<span id="error2" ></span>

function validatePhone() {
phoneNumber = document.getElementById("phone");
var result = phoneNumber.value.match(/^(\d{3}-\d{3}-\d{4})?$/);
if (result == null) {
error2.innerHTML = "The number is not in a correct format";
} else {
error2.innerHTML = " ";
};
}
<p>Phone:</p>
<input type="text" id="phone" name="phone" oninput="validatePhone()">
<br>
<span id="error2"></span>

The problem is with the phoneNumber.toString() call.
Calling toString() on a DOM input element does not return the value of the user input. toString() is intended to provide a string representation of the object it is called on, not retrieve a value held by the object.
phoneNumber.value will return the value you are looking for.

Related

How can I check if a variable is a specific type using javascript?

I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)

how to validate input with javascript

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>

How to split string of input tag HTML?

When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>

Form validation woes

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.

Use user info without prompt or confirm?

All I want to do is be able to do is have users submit info and be able to use it - without using prompt.
I would like to have them be able to input and have a different box to be able to give them info based on there info. I.E. 81 is a great number.
var c = prompt("pick a number")
if(c>100){
console.log("110 is to high of a number")
}
This is what I have. I'm used to JavaScript editors and using console.log. I'm looking for a way to do that based on info I receive and be able to give feed back in a different <div> or whatever. Can anyone help?
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="submit" value="submit" />
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert(textbox.value + '\n' + location.value);
}
<input type="button" value="submit" onclick="showConfirmationDialog();" />
If you're using jQuery, you can use a click handler that looks like this:
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Here's a fiddle that shows the above code in action.

Categories