Form validation is ignoring validation for "name" input - javascript

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,

Related

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>

Using JavaScript to validate a HTML form

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>

JS Function is invoked but no result

When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

Javascript How to use multiple function in html form submission to validate

Html form driving me crazy.
I have a function that checks for mismatch passwords and if the username specified is already taken.
If you pass both of these checks then the form should submit, but it isn't.
It's not a db problem. I've checked that and it connects just fine.
The post in checkname and the post in the form both work when removing the double onsubmit argument. If anyone has any ideas please let me know :)
Here is link of the project I am currently working :
Functions and form:
function validatePassword() {
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("confirm_password").value;
if (pass1 != pass2) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("confirm_password").style.borderColor = "#E34234";
return false;
} else {
return true;
}
}
function checkname() {
var name = document.getElementById("username").value;
if (name) {
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
user_name: name,
},
success: function(response) {
$('#name_status').html(response);
if (response == "OK") {
return true;
} else {
return false;
}
}
});
} else {
$('#name_status').html("");
return false;
}
}
function checkall() {
var namehtml = document.getElementById("name_status").innerHTML;
if ((namehtml) == "OK") {
return true;
} else {
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<font size=4><b>Customer sign up</b></font>
<form name="input" action="customer_insert.php" onsubmit=" return !!(validatePassword() & checkall());" method="post">
<br> Username: <input type="text" maxlength="45" name="username" id="username" onchange="checkname();" required="required">
<span id="name_status"></span>
<br> Password: <input type="password" maxlength="128" name="passwd1" id="password" required="required">
<br> Retype Password: <input type="password" maxlength="128" name="passwd2" id="confirm_password" required="required">
<br> First Name: <input type="text" maxlength="45" name="firstname" required="required">
<br> Last Name: <input type="text" maxlength="45" name="lastname" required="required">
<br> E-mail: <input type="email" name="email" required="required">
<input type="submit" name="Signup" value="Signup">
</form>
Fixed it. Problem was directly using checkname() in the condition results in undefined return and therefor, the condition could never be met. Now I take part of the old checkall() and integrated it with your validate method. This works. Thanks!
function validateForm(){
var a = validatePassword();
var b;
var namehtml=document.getElementById("name_status").innerHTML;
if(namehtml=="OK")
{
b = true;
}
else
{
b = false;
}
if(a && b){
return true;
}
else{
return false;
}
}

Categories

Resources