Using JavaScript to validate a HTML form - javascript

I'm fairly new to JavaScript and HTML. I am trying to validate a feedback HTML form using JavaScript. Although the code should display alerts if the input boxes are empty, no alerts are shown. I have researched the issue and made amendments to my code, however none of these seem to have worked.
JavaScript code:
function validateForm() {
var firstName = document.forms['feedback']['firstName'].value;
if (firstName == null || firstName == "") {
alert("First name is required");
return false;
}
var lastName = document.forms['feedback']['lastName'].value;
if (lastName == null || lastName == "") {
alert("Surname is required");
return false;
}
var email = document.forms['feedback']['email'].value;
if (email == null || email == "") {
alert("Email address is required");
return false;
}
var date = document.forms['feedback']['date'].value;
if (date == null || date == "") {
alert("Date accessed is required");
return false;
}
var tips = document.forms['feedback']['tips'].value;
if (tips == null || tips == "") {
alert("Web design tips is required");
return false;
}
return true;
}
HTML code:
<form name="feedback" onsubmit="return validateForm">
First name: <input type="text" name="firstName" id="firstName">
<br /> Surname: <input type="text" name="lastName" id="lastName">
<br /> Email address: <input type="text" name="email" id="email">
<br /> Date accessed: <input type="date" name="date" id="date">
<br /> Web design tips: <textarea name="tips" id="tips"></textarea>
<br />
<button>Submit</button>
</form>
Thanks in advance!

You are not actually calling your function, you should have return validateForm(); to call it:
function validateForm() {
var firstName = document.forms['feedback']['firstName'].value;
if (firstName == null || firstName == "") {
alert("First name is required");
return false;
}
var lastName = document.forms['feedback']['lastName'].value;
if (lastName == null || lastName == "") {
alert("Surname is required");
return false;
}
var email = document.forms['feedback']['email'].value;
if (email == null || email == "") {
alert("Email address is required");
return false;
}
var date = document.forms['feedback']['date'].value;
if (date == null || date == "") {
alert("Date accessed is required");
return false;
}
var tips = document.forms['feedback']['tips'].value;
if (tips == null || tips == "") {
alert("Web design tips is required");
return false;
}
return true;
}
<form name="feedback" onsubmit="return validateForm();">
First name: <input type="text" name="firstName" id="firstName">
<br /> Surname: <input type="text" name="lastName" id="lastName">
<br /> Email address: <input type="text" name="email" id="email">
<br /> Date accessed: <input type="date" name="date" id="date">
<br /> Web design tips: <textarea name="tips" id="tips"></textarea>
<br />
<button>Submit</button>
</form>

Related

Trying to validate username and password in javascript but not getting alert and desired output

please check the code
function validate() {
var name = document.getElementById("name");
var pwd = document.getElementById("pwd");
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name === null || name === "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
There's a much easier way to do what you are trying to do. You can use the native properties of form to your advantage:
<form>
Username: <input type="text" minlength="2" required>
<br> Password: <input type="password" minlength="6" required>
<br>
<button type="submit">Submit</button>
</form>
HTML elements should be before javascript, like this:
<!DOCTYPE html>
<html>
<body>
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
<script>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</body>
</html>
You haven't provided the full code, so we can't really help you. As far as i can see you didn't make the alert for succesful validation.
You need to get the value, so you need to add .value to the getElement functions.

Not able to match patterns in HTML and JAVASCRIPT

Guys I coded this in html and js. It is just simple three inputs, NAME, EMAIL and PASSWORD. I validated this simple form in javascript but it is not working as expected. I wanted that if I give wrong input to any one of three inputs, it should alert me "Please enter valid credentials." and if I give right input to all of these, It should alert me "Congrats! your form submitted.".
The validation which I gave to NAME field is if length of name is less than 1, it should return false, else true. The validation which I gave to PASSWORD field is same as NAME field and you can see the validation which I gave to all field in my code below. When I give wrong input to only one field, it is still showing me "Congrats! your form submitted."
It is not working as expected!
function ValidateForm(username, email, password)
{
if ((validateusername(username) || validateemail(email) || validatepassword(password))==false)
{
alert("Please Enter Valid Credentials.")
return false
}
else if ((validateusername(username))==true && (validateemail(email))==true && (validatepassword(password))==true)
{
alert("Congrats! your form submitted.")
}
}
function validateemail(email)
{
var x = email.value;
var atposition = x.indexOf("#");
var dotposition = x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
return false;
}
else
{
return true
}
}
function validateusername(username)
{
if (username.length<1)
{
return false;
}
else
{
return true
}
}
function validatepassword(password)
{
if (password.length<1)
{
return false;
}
else
{
return true
}
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit" onclick="ValidateForm(document.myForm.Name, document.myForm.EmailAddr, document.myForm.Password)">Submit</button>
</form>
The problem is your if statement condition.
(validateusername(username) || validateemail(email) || validatepassword(password))==false
is the same as
!validateusername(username) && !validateemail(email) && !validatepassword(password)
so you're saying it should only be considered invalid if all 3 validations fail.
This function can be cleaned up and fixed at the same time:
function ValidateForm(username, email, password)
{
if (!validateusername(username) || !validateemail(email) || !validatepassword(password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
That's all you need. If any one of those fails, then the form fails. Otherwise (else) it's fine. You don't need to re-check again.
One improvement you can make is to take as few arguments as necessary without impeding clarity. This function is called "validate form" so I'd expect the form to be the argument, like this:
ValidateForm(document.myForm)
Which is easy to accommodate internally:
function ValidateForm(form)
{
if (!validateusername(form.username) || !validateemail(form.email) || !validatepassword(form.password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
Which requires renaming your form fields to be consistent:
<input type="text" name="name" placeholder="Enter Name">
<input type="text" name="email" placeholder="Enter Email">
<input type="text" name="password" placeholder="Enter Password">
Tip: Try and have one and only one name for your things. Calling it variously Name or name is really counter-productive.
I would avoid inlining events.
Take a look.
document.myForm.addEventListener("submit", validateForm);
function validateForm(event) {
event.preventDefault();
const {
Name: username,
EmailAddr: email,
Password: password,
} = document.myForm;
if (!validateUsername(username) ||
!validateEmail(email) ||
!validatePassword(password)) {
console.log("Please Enter Valid Credentials.")
return;
}
console.log("Congrats! your form submitted.");
}
function validateEmail(emailField) {
const x = emailField.value;
const atposition = x.indexOf("#");
const dotposition = x.lastIndexOf(".");
if (atposition < 1 ||
dotposition < atposition + 2 ||
dotposition + 2 >= x.length) {
return false;
}
return true
}
function validateUsername(username) {
if (username.length < 1) {
return false;
}
return true;
}
function validatePassword(password) {
if (password.length < 1) {
return false;
}
return true;
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit">Submit</button>
</form>

Form validation is ignoring validation for "name" input

I'm making a form for a project and the form needs to have validation. The validation is working fine for email and institution, but it seems to ignore the name validation. Can someone please help?
var name = document.forms["download__form"]["name"],
email = document.forms["download__form"]["email"],
institution = document.forms["download__form"]["institution"];
function validation() {
if(name.value == "") {
window.alert("Name must be filled!");
return false;
}
if(email.value == "") {
window.alert("Name must be filled!");
return false;
}
if(email.value.indexOf("#", 0) < 0) {
window.alert("Name must be filled!");
return false;
}
if(email.value.indexOf(".", 0) < 0) {
window.alert("Name must be filled!");
return false;
}
if(institution.value == "") {
window.alert("Name must be filled!");
return false;
}
}
<form class="form__fill" name="download__form" onsubmit="return validation()">
<input type="text" class="form__input" name="name" placeholder="NAME*" />
<input type="text" class="form__input" name="email" placeholder="EMAIL*" />
<input type="text" class="form__input" name="institution" placeholder="INSTITUTION/ORGANIZATION*" />
<p>*Must be filled</p>
<input type="submit" name="download" class="form__button" id="form__button" value="Download.PDF" />
</form>
<form class="form__fill" name="download__form" onsubmit="return validation()">
<input type="text" class="form__input" name="name" placeholder="NAME*" />
<input type="text" class="form__input" name="email" placeholder="EMAIL*" />
<input type="text" class="form__input" name="institution" placeholder="INSTITUTION/ORGANIZATION*" />
<p>*Must be filled</p>
<input type="submit" name="download" class="form__button" id="form__button" value="Download.PDF" />
</form>
<script type="text/javascript">
// Javascript
var name = document.forms["download__form"]["name"],
email = document.forms["download__form"]["email"],
institution = document.forms["download__form"]["institution"];
function validation() {
if(name.value == "") {
window.alert("Name must be filled!");
return false;
}
if(email.value == "") {
window.alert("email must be filled!");
return false;
}
if(email.value.indexOf("#", 0) < 0) {
window.alert("email must be valid");
return false;
}
if(email.value.indexOf(".", 0) < 0) {
window.alert("email must be valid");
return false;
}
if(institution.value == "") {
window.alert("institution must be filled!");
return false;
}
}
</script>
There is nothing wrong with your code.. The email validation is creating confusion as you have a same alert value for all the alerts the same. Just enter the email address correct and code will work fine.I have changed the values for u too
It is working fine. You have put all the alert messages as Name must be filled. Therefore if any field gives error it alerts Name must be filled. Just change the alert message related to specific fields and it wont give unnecessary error for name field
var name = document.forms["download__form"]["name"],
email = document.forms["download__form"]["email"],
institution = document.forms["download__form"]["institution"];
function validation() {
if(name.value == "") {
window.alert("Name must be filled!");
return false;
}
if(email.value == "") {
window.alert("Email must be filled!");
return false;
}
if(email.value.indexOf("#", 0) < 0) {
window.alert("Email format is not correct!");
return false;
}
if(email.value.indexOf(".", 0) < 0) {
window.alert("Email format is not correct!");
return false;
}
if(institution.value == "") {
window.alert("Institution must be filled!");
return false;
}
}
<form class="form__fill" name="download__form" onsubmit="return validation()">
<input type="text" class="form__input" name="name" placeholder="NAME*" />
<input type="text" class="form__input" name="email" placeholder="EMAIL*" />
<input type="text" class="form__input" name="institution" placeholder="INSTITUTION/ORGANIZATION*" />
<p>*Must be filled</p>
<input type="submit" name="download" class="form__button" id="form__button" value="Download.PDF" />
</form>
The problem here is that your name control doesnot have a value and also not initialized and hence it is returning undefined when no value if typed. You need to put the check like
if(typeof name.value == "undefined" || name.value =="")
and also you need to follow the suggestion people have given here as changing the message for different type of validations.
Hope this helps,

Javascript validation for email making issues

In my project, I am doing a JS validation for registration purpose. But the validation fails after the email validation. Upto the email validation, it works fine. But after that it is not showing any alerts for rest of validation code.
function signup() {
var signupFullName = $("#signup-full-name");
var signupName = $("#signup-login-name");
var signupEmailAddress = $("#signup-email-address");
var signupPhoneNumber = $("#signup-phone-number");
var signupPassword = $("#signup-password");
var signupConfirmPassword = $("#signup-confirm-password");
var signupAcceptTerms = $("#signup-accept-terms");
if (signupFullName[0].value == "" || signupFullName[0].value == null) {
//alert("Please enter a valid full name.");
alert("Please enter your full name");
signupFullName[0].focus();
return false;
} else if (signupName[0].value == "" || signupName[0].value == null) {
//alert("Please enter a valid login name.");
alert("Please enter your login name.");
signupName[0].focus();
return false;
} else if (signupEmailAddress[0].value == "" || signupEmailAddress[0].value == null) {
//alert("Please enter a valid email address.");
alert("Please enter your email address.");
signupEmailAddress[0].focus();
return false;
}
else if(signupEmailAddress[0].value != "") // problem in this section
{
email=signupEmailAddress[0].value;
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}
}
else if (signupPhoneNumber[0].value == "" || signupPhoneNumber[0].value == null) {
// alert("Please enter a valid phone number.");\
alert("Please enter your phone number.");
signupPhoneNumber[0].focus();
return false;
} else if (signupPassword[0].value == "" || signupPassword[0].value == null) {
//alert("Please enter a valid password.");
alert("Please enter your password.");
signupPassword[0].focus();
return false;
} else if (signupConfirmPassword[0].value == "" || signupConfirmPassword[0].value == null) {
alert("Please confirm the password.");
signupConfirmPassword[0].focus();
return false;
} else if (signupPassword[0].value != signupConfirmPassword[0].value) {
//alert("Please confirm the password.");
alert("Password mismatch");
signupConfirmPassword[0].focus();
return false;
} else if ($("#signup-accept-terms")[0].checked == false) {
alert("Please accept the terms and conditions.");
return false;
} else {
alert("Done");
return false;
}
}
HTML form code:
<form name="signup-form" id="signup-form" method="post" action="<?php echo $site_path; ?>/register" class="form-1" onsubmit="signup();return false;">
<p class="field">
<a href="<?php echo $root_path; ?>">
<img src="<?php echo $theme_path;?>/images/logo.png"/>
</a>
<h4 style="margin-top:10px;color:#208CCD;">Signup</h4>
<br/>
</p>
<p class="field">
<input type="text" name="signup-full-name" id="signup-full-name" placeholder="Full name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-login-name" id="signup-login-name" placeholder="User name">
<i class="icon-signin icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-email-address" id="signup-email-address" placeholder="Email address">
<i class="icon-inbox icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-phone-number" id="signup-phone-number" placeholder="Phone number">
<i class="icon-phone icon-large"></i>
</p>
<p class="field">
<input type="password" name="signup-password" id="signup-password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field" style="margin-top:10px;">
<input type="password" name="signup-confirm-password" id="signup-confirm-password" placeholder="Confirm password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field">
<input type="checkbox" name="signup-accept-terms" id="signup-accept-terms" style="margin-top:10px;color:#B3B3B3">
I accept the Terms and Conditions and the Privacy Policies
</input>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
Can anyone help me to solve this? Thanks in advance.
As I see it it's because you use if/else to check validity of the fields.
So the code picks one error at a time - if any. While you should have something like a for-loop across all the fields you want to validate
I mean it picks this
} else if(signupEmailAddress[0].value != "") {
but does not fall into inner check anymore
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
because email is ok now
Your problem is this statement:
else if(signupEmailAddress[0].value != "")
Because the email field contains text, this rule is evaluated as true and so the rest of the else if blocks won't be executed.
I'd consider changing the else if's to be individual if statements so that they won't stop each other.
You have to remove the return false statements inside if condition. Inside validation function, at the end you have to return false if any of the validation fails. Here's an example to do it:
var result = true;
if(condition 1){ // if condition 1 fails, make result = false;
}
if(condition 1){ // if condition 2 fails, make result = false;
}
if(condition 1){ // if condition 3 fails, make result = false;
}
return result; // After all validations, result result
That's it.
Replace your correction place with this code....
else if(signupEmailAddress[0].value != "" && !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(signupEmailAddress[0].value)) // problem in this section
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}

Why won't this javascript phone field form validator work?

This phone number validator doesn't work :/. Why?
Ideally, if the optional phone field is not null, it should proceed to validate the form.
The phone field is optional, and isn't required.
Validating the form:
the phone field is optional. this means that it is not required.
it should ignore comparing everything except numbers.
if the digit count is != 10 numbers, it should display the error.
if the count is equal to 10 digits, it should pass onto name.php (see the HTML)
Javascript Code:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
var regExpressionValue = /[^\d.]/g;
if (formValue !== null)
{
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}
HTML:
<form class="form" id="form" name="form" method="post" action="name.php" onsubmit="return validateForm()" />
<input type="text" name="name" id="name" />
<input type="text" name="email" id="email" />
<input type="tel" name="number" id="number" />
<button type="submit" value="Send" />Sign Up</button>
<div class="spacer"></div>
</form>
Your regular expression is wrong. Try this instead
if (/^\d{10}$/.test(formValue) === false) {
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
You have bad regexp and string presence check for phone number. Check this out:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
if (formValue)
{
var regExpressionValue = /^(\d-?){10}$/g;
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}

Categories

Resources