javascript form validation not working and can't fin why - javascript

So I have this html:
<form action="insert.php" method="post" onsubmit="return validateForm(this)">
<label for="FUP start date">FUP start date:</label>
<input type="text" name="inputField" id="inputField"/>
</br>
</br>
<label for="FUP end date">FUP end date: </label>
<input type="text" name="inputField2" id="inputField2" />
</br>
</br>
<label for="Allowed traffic">Allowed traffic:</label>
<input type="text" name="Allowed_traffic" id="Allowed_traffic"/>
</br>
</br>
<label for="Frequency">Frequency: </label>
<input type="text" name="Frequency" id="Frequency" />
</br>
</br>
<input type="submit" value="submit">
</form>
And this javascript for password (Parola):
<script>
function validateForm(formElement) {
if (formElement.Allowed_traffic.length < 5) {
alert('aaaPlease enter a password that is at least 5 characters long');
return false;
}
if (formElement.Allowed_traffic.length > 10) {
alert('Please enter a password that is less than 10 characters long');
return false;
}
}
</script>
What am I doing wrong? I want to check on submit that the password has between 5 and 10 characters.
Thank you!

Replace .length with .value.length.

You're currently looking at the length property of the <input> element itself (which probably doesn't exist). What you want to be looking at is the length property of the value of the <input> element, so do the following:
if (formElement.Allowed_traffic.value.length < 5) {
alert('aaaPlease enter a password that is at least 5 characters long');
return false;
}
else if (formElement.Allowed_traffic.value.length > 10) {
alert('Please enter a password that is less than 10 characters long');
return false;
}
Note that I've changed it to an if ... else if because if the first condition is true then the second one can't be.

Try to use
var Allowed_traffic = document.getElementById("Allowed_traffic");
instead of
formElement.Allowed_traffic

Related

How do I stop repeated execution of alert() inside an if statement in javascript?

var inputs = document.querySelectorAll('.credentials input');
function checkCredentials(){
inputs.forEach(function(input){
if(input.value=="" && !alert('please enter a valid card number')){
alert('please enter a valid card number');
}
else{
alert("payment successful");
}
})
}
<div class="card-container">
<div class="card-img">
<img src="visa.png">
</div><!-- card img -->
<div class="credentials">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="text" name="4">
<input type="text" name="5" class="fifth-input">
<input type="text" name="6">
<input type="text" name="7">
<input type="text" name="8">
<input type="text" name="9" class="ninth-input">
<input type="text" name="10">
<input type="text" name="11">
<input type="text" name="12">
<input type="text" name="13" class="thirteenth-input">
<input type="text" name="14">
<input type="text" name="15">
<input type="text" name="16">
</div><!-- credentials -->
<div class="btn">
<button onclick="checkCredentials();">Click to Proceed</button>
</div><!-- btn -->
</div><!-- card container -->
I have a 16 inputs each input field with maximum one digits, what I want is, On click of a button
-If any of the input field is empty the an alert box saying 'please enter a valid card number must display' once and page be reloaded.
-else an alert box saying 'payment successful' displayed once and page reloaded.
You can try this:
var inputs = document.querySelectorAll('.credentials input');
let numberVar;
function checkCredentials(){
numberVar = 0;
inputs.forEach(function(input){
if(input.value=="" && numberVar++ < 1){
alert('please enter a valid card number');
}else{
alert("payment successful");
}
})
}
But if you need to go through all the inputs and show which value is not filled, then you need a different approach. And also the expression needs to be rewritten in the same way.
You can filter the Array for the given criteria and check if the Array is empty or not.
I would also suggest to use input Parameters for functions and not use global Variables =)
Example:
function checkCredentials(inputs){
const containsEmptyInputs = inputs.filter(i => i == "").length > 0;
const message = containsEmptyInputs ? 'please enter a valid card number' : 'payment successful';
alert(message);
}

Trigger action in form submit javascript html

I am trying to validate the fields in the form and pull up a different html file when the user clicks the submit button if there's no error in field validation.
However, the validators don't seem to work. I want the Event Name and Location fields to alphanumeric characters and spaces, but it seems to take other values as well.
Putting onClick="self.location='successPage.html'" inside the submit button does not seem to validate the fields either. I want it to move to the successPage.html file if all fields in the form are successfully validated.
I don't want to use jQuery.
Here is my code:
<form action="" >
<p>
<label>
Day of the week:<br>
<select name="days">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select><br>
</label>
<label>
Start Time:<br>
<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
</label>
<label>
End Time:<br>
<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
</label>
<label>
Event Name:<br>
<input id="ename" type="text" name="ename" required /><br>
</label>
<label>
Location:<br>
<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9\s]"-->
</label>
<label>
Enter URL for the pictture:<br>
<input id="urlpic" type="text" name="urlname" />
</label>
<br><br>
<input type="reset" id="reset" value="Reset" />
<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
</p>
</form>
<script>
function chkName() {
var myName = documnet.getElementById("ename");
var pos = myName.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myName + ") again");
return false;
} else
return true;
}
function chkLoc() {
var myLoc = documnet.getElementById("loc");
var pos = myLoc.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myLoc + ") again");
return false;
} else
return true;
}
document.getElementById("ename").onchange = chkName;
document.getElementById("loc").onchange = chkLoc;
</script>
<form action="." method="POST" onsubmit="return validate(this)">
<input type="submit" value="Submit">
</form>
the form element will be passed into the validate function when the user submits, return false to not submit the form, and true to submit it.
<script>
function validate(form) {
console.log(form); // log element to console on submit
return false; // replace with true if input is good to be submitted
}
</script>

Check fields contain data and that one is a number

New to javascript but I am trying to check if three fields (1) contain some data and that (2) the third one contains any numbers. The third one is a telephone # field. I realize dashes would be involved. And that the form could validate if a user entered only one number or a number and some text. But I'm starting small. Any help would be great.
function validate(){
if ((document.myForm.fname.value=="") || (document.myForm.lname.value=="")
|| (document.myForm.telenumber.value=="")){
alert("You must fill in all of the required fields!")
return false
}
else
return true
}
<form name="myForm" onsubmit="return validate()">
<label for="fname">First name</label>
<input type="text" id="fname" name="firstname"><BR>
<label for="lname">Last name</label>
<input type="text" id="lname" name="lastname"><BR>
<label for="tele">Telephone number</label>
<input type="text" id="tele" name="telenumber">
<input type='submit' value='Submit' /><br />
</form>
I would use the typeof function to check if fname and lname are strings plus a regular expression to check if the phone number format is valid.
Working code example:
(function(){
function validate(e) {
e.preventDefault();
var fname = document.getElementById('fname').value,
lname = document.getElementById('lname').value,
phone = document.getElementById('tele').value;
//regex example for phone number format
var regex = new RegExp('^((([0-9]{3}))|([0-9]{3}))[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4}$');
//Validation
if(typeof fname === 'string' && typeof lname === 'string' && regex.test(phone))
console.log('Ok. valid user data');
else
alert('Invalid user data!');
}
// Event listner for form submission
document.getElementById('myForm').addEventListener('submit', validate);
})();
<form name="myForm">
<label for="fname">First name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last name</label>
<input type="text" id="lname" name="lastname">
<label for="tele">Telephone number</label>
<input type="text" id="tele" name="telenumber">
<input type='submit' value='Submit' />
</form>
Additional Note:
I'm checking the form controls to be string with typeof for more code clarity, but it is redundant as the form control are always type string.
So if you want the validation condition can be just if(regex.test(phone))

How to validate with Javascript?

Thanks to having to work so much, I am completely confused on JavaScript. I have tried so many things and have not gotten my form to validate even once. I have to use plain JavaScript to:
**Validate the email - the email must have # and the domain should be yahoo.com
Phone No.: Must contain exactly 10 digits
Age: Must be a positive number less than 120
The validation should happen when the user submits the form. In case any of the above validation fails, the corresponding fields should be highlighted in red
If the validation is successful, the page should redirect to http://yahoo.com**
I'm not looking for someone to necessarily give me the exact answer, but push me in the right direction, because I do have a basic understanding of JS.
<!DOCTYPE HTML>
<div id="form">
<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function ValidatemyForm()
{
var email = document.myForm.email;
var phone = document.myForm.phonenumber;
var age = document.myForm.age;
}
{
age = age.replace(/[^0-9]/g, '');
if(age.length != 10)
{
alert("not 10 digits");
}
else {
alert("yep, its 10 digits");
}
}
</script>
</head>
<div id="header">
<hr id="HR1">
<h1> Web Programming: Assignment 3 </h1>
<p> Form Validation with Javascript </p>
<hr id="HR2">
</div>
<div id="input">
First name: <br>
<input type="text" name="firstname">
<br>
Last name: <br>
<input type="text" name="lastname">
<br>
FSU Email: <br>
<input type= "text" name="email">
<br>
Phone No.: <br>
<input type="numbers" name="phonenumber">
<br>
Age: <br>
<input type="numbers" name="age">
</div>
<hr id="HR3">
<br>
<div id="Sex">
Sex: <br>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br>
<input type="radio" name="sex" value="other"> Other
</div>
<hr id="HR32">
<div id="languages">
Programming languages you want to learn: <br>
<input type="checkbox" name="python" value="python"> Python
<br>
<input type="checkbox" name="java" value="java"> Javascript
<br>
<input type="checkbox" name="C++" value="C++"> C++
<br>
<input type="checkbox" name="lisp" valie="lisp"> Lisp
</div>
<hr id="HR32">
<div id="submit">
<input type="Submit" value="Submit">
</div>
<hr id="HR12">
</form>
</div>
Aneshia,
You have a few problems. First the function listed in the "onsubmit" attribute of your form does not match your javascript function. Also there are some problems with your {} braces. After you get that fixed be sure to call .value after your form elements to get the value of the input ie. (document.myForm.email.value).
Here is the code with some fixes:
<form name="myForm" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function validateForm() {
var email = document.myForm.email.value;
var phone = document.myForm.phonenumber.value;
var age = document.myForm.age.value;
console.log(age)
var okToSubmit = true;
age = age.replace(/[^0-9]/g, '');
if (age.length != 10) {
alert("not 10 digits");
okToSubmit = false;
} else {
alert("yep, its 10 digits");
}
if (age > 120 || age < 0) {
alert("Must be a positive number less than 120");
okToSubmit = false;
}
return okToSubmit;
}
Another thing that may help is to bring up the javascript console in your browser and run your function manually in the console by typeing 'validateForm();'
You may be intrigued to note that html5 now validates some of these forms so you do not need to use Javascript.
See HTML Form Validation
You asked about email, age and phone.
Consider the following examples::
<form>
<input type="email" name="email" pattern=".*#yahoo\.com"> <br>
<input type="number" min="18" max="120" name="age"> <br>
<input type="tel" name="phonenumber"> <br>
<input type='submit'>
</form>
If you want the fields to be required you could use
<form>
<input type="email" name="email" pattern=".*#yahoo\.com" required> <br>
<input type="number" min="18" max="120" name="age" required> <br>
<input type="tel" name="phonenumber" required> <br>
<input type='submit'>
</form>
See http://diveintohtml5.info/forms.html
In your comments a few days later, you mentioned needing to do this in Javascript. I think the best way is still using HTML5 and a clever way to do this if you have to use javascript might be to set the input attributes through javascript. Something like this could get you started on the logic.
While I generally do not like getting this specific in the code, I commented things so you can get a general feel for how you can work with data in javascript.
function validate(event){
// First we stop the form from even submitting until we run the code below
event.stopPropagation();
// Here we are going to place a reference to the objects we want to validate in an array
var references = ['email','age','phonenumber'];
// Now we are going to grab our list of inputs from the page
var inputs = document.getElementsByTagName('input');
// We run through a for loop to look for specific elements
for(i = 0; i < inputs.length; i++){
/*
This line simply asks, is the 'name' of this element inside our references array.
This works by using the indexOf function which is built into Javascript.
indexOf simply provides the index where it finds the phrase you are looking for.
In this example, we are using it to see if an index exists by checking it against negative 1
*/
if(references.indexOf(inputs[i].getAttribute('name')) > -1){
// A switch block lets you present a different outcome based on the criteria being looked for
switch(inputs[i].getAttribute('name')){
// In this case we see if we get an email named element
case 'email':
// We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
inputs[i].setAttribute('type','email');
inputs[i].setAttribute('pattern','.*#yahoo\.com');
break;
case 'age':
inputs[i].setAttribute('type','number');
inputs[i].setAttribute('min',18);
inputs[i].setAttribute('max',120);
break;
case 'phonenumber':
inputs[i].setAttribute('type','tel');
break;
}
// When we are all done, we set the elements to be required
inputs[i].setAttribute('required',true);
}
}
// Now we submit the form
event.submit();
}
<form>
<input type="text" name="email"> <br>
<input type="text" name="age"> <br>
<input type="text" name="phonenumber"> <br>
<input type='submit' onclick='validate(event)'>
</form>
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

Checking blank field in text area

I have 3 text box and 1 textarea field.
id, name, address, contact.
All are java scripted in the purpose of checking blank field.
I did it in this way :
javascript code :
function checkForm()
{
var id=document.getElementById("id").value;
var name=document.getElementById("name").value;
var address=document.getElementById("address").value;
var contact=document.getElementById("contact").value;
if(id.length<1 )
{
alert("Please enter all the informations!");
return false;
}
if(name.length<1 )
{
alert("Please enter the name!");
return false;
}
if(address.length<1 )
{
alert("Please enter the address!");
return false;
}
if(contact.length<1 )
{
alert("Please enter the contact!");
return false;
}
html code :
<form method="post" action="clients.php" onSubmit="return checkForm()">
id <input type="text" name="id" id="id">
name <input type="text" name="name" id="name">
address <textarea name="address" id="address"> </textarea>
contact <input type="text" name="contact" id="contact">
<input type="submit" name="submit" value="Enter">
</form>
All are working except textarea. I am trying with some other code, founded in the internet, but those aren't working. Maintaining the serial (id then name then address then contact....) how can i check the blank space of the textarea?
Thanks a lot in advance.
Use trim function to remove whitespaces
var id=document.getElementById("id").value.trim();
var name=document.getElementById("name").value.trim();
var address=document.getElementById("address").value.trim();
var contact=document.getElementById("contact").value.trim();

Categories

Resources