Correcting Form Error - javascript

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>

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>

Need help javascript

I want to know that in the following code, when I reference an element
by (document.getElementById) and make it equal to a variable for the validation purpose why I can't use the name instead of name1 in javascript.
function validation() {
name1 = document.getElementById('name');
if (name1.value == "") {
alert('this field cannot left empty');
return false;
}
}
<form id="form" action="message.html" method="post" onSubmit='return validation()' />
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">
After adding var to name1 the code will start executing. After adding var you can assign the document.getElementById('name') to name also and it would work. You can run the below snippet for reference.
function validation(){
var name=document.getElementById('name');
if(name.value== ""){
alert('this field cannot left empty');
return false;
}
}
<form id="form" action="message.html" method="post"
onSubmit='return validation()'>
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">
</form>
var name=document.getElementById('name');
You should use var before an element name.
Try using this..
You forgot to declare the variable.
If you are using a variable for assignment you must declare it before using.
For more reference you can look up this popular thread in SO, What is the purpose of the var keyword and when to use it (or omit it)?
function validation(){
var name = document.getElementById('name');
if(name.value== ""){
alert('this field cannot left empty');
return false;
}
}

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/

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

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Categories

Resources