id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link
Related
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)
The code should validate that the input fields dont contain a number and only letters and also both fields arent blank. Currently it works with detecting if they aren't blank but it only detects a number in 'firstname' - I have managed to get one or the other working but never both at the same time. Help!!
Also, If the validation fails the joke shouldn't be returned (the button onclick provides the joke by using the first and last name and sending it to an api to retrieve the joke).
function validateForm() {
var firstname = document.getElementsByName("firstname")[0].value;
var lastname = document.getElementsByName("lastname")[0].value;
var input = document.getElementsByName("firstname" && "lastname");
if (firstname == "" && lastname == "") {
alert("Please enter atleast one name");
}
else if (!(/^[a-zA-Z]+$/.test(firstname || lastname))) {
alert("'Only alphabets allowed'");
}
}
return (
<div className="jokeForm" >
<form name="searchForm" >
<input type="text" name="firstname" placeholder="First name" value={firstname} onChange={(e) => setFN(e.target.value)} />
<input type="text" name="lastname" placeholder="Last name" value={lastname} onChange={(e) => setLN(e.target.value)} />
</form>
<button onClick={() => validateForm(newJoke(firstname, lastname))}>click here for a personalised chuckle</button>
<h3>{joke}</h3>
</div >
)
}
Use + to add both strings together. And do test with Regex. eg.
var firstname="j";
var lastname="k1";
if (!(/^[a-zA-Z]+$/.test(firstname + lastname))) {
alert("Only alphabets allowed!");
}
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 have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}
I've used JavaScript to ensure that the fields on my form are correctly filled out (required fields with correct type of information) and the browser seems to ignore the rules I set and process the information anyway.
HTML
HTML
<form id="course-form" name="courseForm" method="POST" onSubmit="return checkCourse()" action="#">
<label for="courseName">Course Name: </label>
<input type="text" id="course-name" name="courseName" placeholder="Course Name" required/><br/>
<br>
<label for="qualDesc">Description: </label><br/>
<textarea name="qualDesc" class="boxsizingBorder" placehold
<label for="entryReqs">Entry Requirements</label><br>
<textarea name="entryReqs" class="boxsizingBorder" id="entry-reqs" placeholder="Previous Grades Required" required></textarea><br>
<br>
<label for="cost">Cost: £</label>
<input type="text" name="cost" id="courseCost" maxlength="6" size="5" required/><br>
<br>
<input type="submit" value="Add Course" />
</form>
JavaScript(Placed in Head of document)
<script>
function checkCourse()
{
var date = new Date();
var year = (date.getFullYear());
var courseName=document.forms["courseForm"]["courseName"].value;
var courseDesc=document.forms["courseForm"]["qualDesc"].value;
var courseYear=document.forms["courseForm"]["year"].value;
var entryReqs=document.forms["courseForm"]["entryReqs"].value;
var cost=document.forms["courseForm"]["cost"].value;
if(courseName == "")
{
alert("Course name is a required field.");
return false;
}
else if(courseDesc=="")
{
alert("The Course needs a description");
return false;
}
else if(courseYear < year)
{
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);
return false;
}
else if(entryReqs=="")
{
alert("You must enter some entry requirements");
return false;
}
else if(isNaN(cost) || (cost==""))
{
alert("Cost is not a valid numerical figure");
}
alert("Course added sucessfully!");
return true;
}
</script>
**Note, I've also tried putting the return true section in an else statement like this:
else
{
alert("Course added sucessfully!");
return true;
}
Am I missing something?
Thanks
In the line below, you try to get the value of an input, but your form does not contain an input that is named year. This will cause a Javascript error and subsequently, your validation will be disregarded and the form will continue to submit
var courseYear=document.forms["courseForm"]["year"].value;
A second problem is you don't return false if the cost validation fails (but this is not your root problem).
Also as juvian points out, you are missing a closing quote on the alert below:
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);