Validate HTML form input with JavaScript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
I have an HTML form that uses PHP/MySQL to post to a database. In the email section of the form, I want the user to be displayed an error message if he or she types in an email address that is not in valid email address format. I am modeling off of a code like this, but I cannot get it work.
Note that whenever I hit the submit button on the form, the form submits, and the PHP action works fine. The problem is I can enter anything I like in the form and it will pass fine. I would like for it to display the error message "Not a valid email address". I understand I can validate via PHP too, but I would like to validate on the client side as well.
Can anyone assist?
<script type="text/javascript">
function validateEmail()
{
var x=document.forms["test"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<form name"test" action="roads.php" onsubmit="return validateEmail();" method="post">
<input type="text" name="email" placeholder="Enter your e-mail" />
<input type="submit" value="Show Me!" />
</form>

you are missing a = in html, which doesn't make to form name test..and javascript can't find the form of name test, and throws error...check console log for javascript errors..
<form name"test" action="roads.php" onsubmit="return validateEmail();" method="post">
<form name="test" action="roads.php" onsubmit="return validateEmail();" method="post">
Working code

Here is a better way to access the form and its fields - also remember to return true
Assuming <form id="testform" action="roads.php" method="post">
we can use unobtrusive scripting
<script>
window.onload=function() {
document.getElementById("testform").onsubmit=function () {
var email=this.email.value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
}
</script>

Related

JavaScript Login Form Not Validating

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

Refresh jquery form after submission not working

For one of my websites, I am designing a HTML form with jquery and PHP for sending the data through email.
The Jquery, checks for the empty /blank fields and sends alerts for each filed.
Once the form is submitted with full data, it sends success alert and send the input data through PHP.
Till this point the code works fine.
Once the data is submitted & success alert is shown, I want the html form to be refreshed / reloaded.
But this this not happening, as the form remains with the pre-entered data.
Kindly help me in this please. My Jquery & HTML form is given below.
JQUERY-CODE (with google libs 2.2)
JQUERY CODE
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '') {
alert(" Please fill your name");
} else if (email == '') {
alert("Please fill your email");
} else if (message == '') {
alert("Please Fill message");
} else { alert("Your form submitted. We will contact you soon.");
$.post("xxx.php", { // To php file.
name: name,
email: email,
message: message
}, function(data) {
$("#returnmessage").append(data);
if (data == "Your form submitted. We will contact you soon.") {
$("#form")[0].reset(); // To reset form fields on success.
}
});
}
});
});
HTML FORM CODE:
<form id="form" method="post" action=" ">
<h4>FEED-BACK FORM</h4>
<p id="returnmessage"></p>
<label>Name: </label>
<input type="text" id="name" /><br>
<label>Email: </label>
<input type="text" id="email" /><br>
<label>Message: </label>
<input type="text" id="message" /><br>
<input type="button" id="submit" value="Submit"/>
</form>
check below js
if (data == "Your form submitted. We will contact you soon.") {
document.getElementById('form').reset(); // To reset form fields on success.
}
Or
if (data == "Your form submitted. We will contact you soon.") {
$('#form').find("input[type=text]").val(""); // To reset form fields on success.
}
you can clear the input fields by setting its value to ""
$("#name").val("");
$("#email").val("");
$("#message").val("");
The problem is most likely with your if statement. The line $("#form")[0].reset(); is correct, move it above the if statement to see it working.

onSubmit button won't load location

I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.

Form submits regardless of validation

I have a form, and I've written a validation script for it, however, it's not working 100%. It outputs errors fine, but the submit button will submit the form, even if it has outputted the alert boxes. Anyone have any idea why?
Apparently not all the code pasted. I would just use the Required parameter, but I need JS validation as it is an assignment. Also, UL is defined before this part of code, as there is a list before this.
HTML:
<div class = "form">
<form name = "contactForm" onsubmit="validateForm()" action = "form.php">
<li><label>First name: </label><input type = "text" name = "fname" autofocus></li><br>
<li><label>Last Name: </label><input type = "text" name = "lname"></li><br>
<li><label>Email: </label><input type = "text" name = "email"> <button onclick = "validateEmail();return false">Check if email is valid</button> </li><br>
<li><label>Message: </label> <br>
<textarea rows = "10" cols = "50" name = "message"></textarea></li>
<li> <input type = "submit"> </li>
</form>
JavaScript:
function validateForm()
{
var x=document.forms["contactForm"]["fname"].value; //Gets the form and field name from the HTML
if (x==null || x=="") //If the field "fname" contains null, or nothing, then output an alert telling the user to input something into the field. Same goes for the rest of the code.
{
alert("First name must be filled out");
return false;
}
var x=document.forms["contactForm"]["lname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["contactForm"]["email"].value;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(x) == false)
{
alert("Please enter a valid Email");
return false;
}
if (x==null || x=="")
{
alert("Email must be filled out");
return false;
}
var x=document.forms["contactForm"]["message"].value;
if (x==null || x=="")
{
alert("Message must be filled out");
return false;
}
}
You have to trigger event on time of submit. Like this way:
<form onsubmit="validateForm()">
How are you attaching the event listener? I’d wager it’s with:
<form … onsubmit="validateForm()">
You’d need return validateForm(). But wait! Don’t add that.
Your script does not check for valid e-mail addresses correctly. It only checks one error at once. It will annoy users. Use HTML5 validation and back it up with PHP.
By applying type="email", you don’t need a button at all, and mobile users will see an e-mail specific keyboard if available. The browser will validate it, given support.
<input type="email" name="email">
Required fields should use the required attribute.
<input type="text" name="fname" autofocus required>
&vellip;
<input type="text" name="lname" required>
Your labels aren’t correct either; they should surround the element they’re related to, or provide a for attribute matching the element’s id.
You should also validate your HTML. And not put <br>s between <li>s.
Finally, as general [client-side] JavaScript tips:
You don’t have to check the value of a text field for null.
Write !x instead of x == false.
You can also use JQuery to do something like this:
$( "#formId" ).submit(function( event ) {
if($("#nameInput").val() == "")
event.preventDefault();
});
So basically, if nameInput's equals to empty the submit action will be canceled
Take a look at here if you want: https://api.jquery.com/submit/
Good luck

jquery valid email check [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
I am just a beginner in jquery.I have used email field in my form. The form shouldn't submit if the email field is empty. I used the following code
if(document.getElementById('emailaddress').value == ''){
alert('Enter the Email Address');
document.getElementById('emailaddress').focus();
return false;
}
How can i check the entered email is a valid one using simple jquery?
Your best bet would be to use the jquery validate plugin.
A live email validation demo can be seen here
Here is some sample code:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" type="text/javascript"></script>
<script>
$(function () {
$("#myForm").validate({
rules: {
emailaddress : {
required: true,
email: true
}
}
});
});
</script>
<form id="myForm">
Email address: <input type="text" name="emailaddress" id="emailaddress" class="required" >
</form>

Categories

Resources