Check fields contain data and that one is a number - javascript

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))

Related

Disable and enable button in js

i want to make a form with inputs and "submit" button. Idea is to disable button as long as inputs are empty or value of input not correctly (email validation).
I have my js code, but the problem is that, button starts at the beggining as disabled, but when i write something in first input it start to be not disabled, even if rest of inputs have not correct value.
My function:
document.getElementById("my-button").disabled = true
function inputValidator() {
var $element = $(this);
// for all input fields
if ($element.val()) {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
} else {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
}
// for email field
if ($element.attr('id') === 'email' && $element.val()) {
if (!reg.test($element.val())) {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
} else {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
}
}
Does anyone knows how to solve it?
Iterate over each element inside the form and check if one elements value length is zero. Note: Also the submit button needs a value in this implementation. A more native way would be to simply add the required tag to each input which also gives a good user experience.
JS approach
function validateForm() {
let inputs = document.forms["example"].elements;
let status = true;
[...inputs].forEach((input) => {
if(input.value.length == 0) status = false;
});
document.getElementById('submit').disabled = !status;
}
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" onKeyup="validateForm()">
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" onKeyup="validateForm()">
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" onKeyup="validateForm()">
</p>
<p>
<button disabled=true id="submit" value="submit">Submit</button>
</p>
</form>
Pure HTML Approach
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" required>
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" required>
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" required>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>

How to validate multiple inputs in a form

Please take a look at this code, I want to know how to validate all these input elements in this single form using JavaScript.
I know they look the same but i have the names in a separate div. Your corrections and contributions to my form will be very much appreciated.
<form name="myForm">
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="password" name="fname"><br><br>
<input type="submit" value="Submit">
</form>
Yes, You can. Try this to Validate data in Java Script
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Then You have to create a javaScript Function to Validate the data as above validateDate(), for this, now your code is
<script>
function validateData() {
var fname = document.getElementById("fname").value;
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
//if name is empty
if(fname == "" || username == "" || email == "" || password == "") {
//SOme Error Code here
alert("Please Fill All the Form Data.");
}
if(username.length < 4 || username.length > 20) {
//SOme Error Code here
alert("username must be less than 20 but more than 4 Characters.");
}
// You can add more filters like password length, and so on by using more if conditions
}
</script>
<body>
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
That's all. :)
Even though this requires jQuery, it can solve your problem:
To use jQuery Validate you just need to include in your code a version of the jQuery library equal or more recent than 1.7 and a file with the plugin.
See an example:
jQuery('form').validate();
After calling the jQuery.fn.validate method, you can validate your fields using data attributes, that are valid to the HTML5, according to the W3C.
See a example to required field:
<form>
<input type="text" data-required />
</form>
https://plugins.jquery.com/validate/

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>

Correcting Form Error

I am trying to make it so that if the user does not enter their first and last name an alert message will occur. The code looks right to me but it is not working.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function func(){
var first = getElementByID("fname").value;
var last = getElementByID("lname").value;
var email = getElementByID("mail").value;
var phone = getElementByID("phone").value;
if ( first == "" && last =="")
{
alert("Please Enter First and Last Name");
}
</script>
</head>
<body>
<form id="survey" name="survey" method="post">
First Name:<br>
<input type="text" id="fname" name="fname"><br>
Last Name:<br>
<input type="text" id="lname" name="lname"><br>
Email:<br>
<input type="email" id="mail" name="mail"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" onclick="func()">
</form>
</body>
use document.getElementById, not getElementByID
The if should use || (OR), not && (AND), so it alerts if either field is empty, not only when both fields are empty.
To keep the form from submitting, the validation function must return false, and the onclick attribute needs to return the value.
It's better to use the form's onsubmit handler than the submit button's onclick handler.
So the JS should be:
function func(){
var first = getElementByID("fname").value;
var last = getElementByID("lname").value;
var email = getElementByID("mail").value;
var phone = getElementByID("phone").value;
if ( first == "" && last =="") {
alert("Please Enter First and Last Name");
return false;
}
}
and the HTML should be:
<form id="survey" name="survey" method="post" onsubmit="return func()">
First Name:<br>
<input type="text" id="fname" name="fname"><br>
Last Name:<br>
<input type="text" id="lname" name="lname"><br>
Email:<br>
<input type="email" id="mail" name="mail"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit">
</form>
if ( first == "" && last =="")
implies that the warning will appear only if first AND last are empty.
Try using:
if ( first == "" || last =="")
use document.getElementById('fname'), not getElementByID
error in your condition, try it with (first == "" || last == "")
(first is empty OR last is empty) -> error
EDIT, code snippet, in your code, there is missing one } at the end of script!
function func(){
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var email = document.getElementById("mail").value;
var phone = document.getElementById("phone").value;
if ( first == "" || last =="")
{
alert("Please Enter First and Last Name");
return false;
}
return true;
}
<form id="survey" name="survey" method="post" onsubmit="return func();">
First Name:<br>
<input type="text" id="fname" name="fname"><br>
Last Name:<br>
<input type="text" id="lname" name="lname"><br>
Email:<br>
<input type="email" id="mail" name="mail"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" value="submit">
</form>

How to validate multiple fieldset in one form tag?

I am working on a form checking. I am stuck on how to stop submitting the form.
So basically, the form has 2 fieldsets (Creat New Customer and Return customer). I have a function which is checking the return customer fieldset if either one of the text field is blank then it will display an message. However, this function also affects on the fieldset (New customer), thus even all the text fields of new customer filled out, it display the message from that function as well. My code:
HTML
<form action="" onsubmit="return loginCheck()">
<fieldset>
<legend>
Create New Account
</legend>
<label>
Account:
<input name="ACCOUNT" size="16" type="text" id="acc"/>
</label>
<label>
Password:
<input name="PW" size="32" type="password" id="pw"/>
</label>
<label>
Password Again:
<input name="PW2" size="32" type="password" id="pw2"/>
</label>
<label>
Email:
<input name="EMAIL" size="32" type="text" id="email"/>
</label>
</fieldset>
<fieldset>
<legend>
Login
</legend>
<label>
Account:
<input name="ACCOUNT" size="16" type="text" id="loginAcc"/>
</label>
<label>
Password:
<input name="PW" size="32" type="password" id="loginPass"/>
</label>
</fieldset>
<input value="Submit" type="submit" id="submit"/>
<input value="Reset" type="reset" id="reset"/>
JS:
function loginCheck() {
var x = document.getElementById("loginAcc");
var y = document.getElementById("loginPass");
if (x.value == "") {
alert("You must type in both fields");
return false;
}
if (y.value == "") {
alert("You must type in both fields");
return false;
}
return true;
}
How can I fix to get that function just check the login fieldset without affect on the create new customer fieldset? Thank you!
You would have to check if the user is trying to enter a new account or his credentials, then check if the form is filled correctly...
function loginCheck() {
var a = document.getElementById("acc");
var b = document.getElementById("pwd");
var c = document.getElementById("pwd2");
var d = document.getElementById("email");
var x = document.getElementById("loginAcc");
var y = document.getElementById("loginPass");
if(a.value!="" || b.value!="" || c.value!="" || d.value!="" ||){
//Do logic to validate creation fieldset.
}else{
//Do logic to validate login
}
return true;
}
There might exist better solutions tough, you could have 2 forms instead of one or something in those lines... What the code above does is really simple, just checks if the user tries to create an account and then validates it. If the user types in his account name in the create form, and notices it is not the right place, then fills the login fields, the script will not work as expected by the user... Try to play with that a bit to find your best solution.

Categories

Resources