I made a contact form for my website and I want to make validations. This is the HTML:
<form name="contact" method="post" action="Contact.php" onsubmit="return validateForm()" >
<span class="formtext"> name:</span> <input id="nameinput" type="text" name="name" /><br />
<span class="formtext"> email:</span> <input id="mailinput" type="text" name="email" /><br />
<span class="formtext"> message:</span><br /> <textarea id="messageinput" type="text" name="message"> </textarea> <br />
<input id="submitinput" name="submit" type="submit" value="שלח"/>
</form>
This is the JS:
// Contact Form //
function validateForm()
{
var x=document.forms["contact"]["name"].value;
var y=document.forms["contact"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
var z=document.forms["contact"]["email"].value;
if (x==null || x=="" || y==null || y=="" || z=="" || z==null)
{
alert("Please fill all the details");
return false;
}
else
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert ("Please fill a valid email address");
return false;
}
}
The problem has something to do with the variable 'z'. When I fill the form and send it, I get the "Please fill all the details" alert, even though I did fill the textarea. I know it's the 'z' because if I remove both the variable and the part inside the 'if' that has something to do with var 'z', the problem is solved- but then there is no validation.
The z also handles the email input instead of the message textarea
Try replacing
var z=document.forms["contact"]["email"].value;
by
var z=document.forms["contact"]["message"].value;
Related
I am trying to get an email validation to work and can't seem to figure out the problem. I want it to alert if what is entered is not a valid email. The code I attached is the email function and the form code for the email. Help is appreciated thanks!
{
var emailfield=document.getElementById("emailaddress").value;
var atpos=emailfield.indexOf("#");
var dotpos=emailfield.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailfield.length){
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
}
Here is the code for the form.
<form action='#' method='post' name='f1' id="VPN" onsubmit='return checkButons(this)'>
Aspects <br>
<input type='radio' name='aspect' id='aspect1' value='security' />Security <br>
<input type='radio' name='aspect' id='aspect2'value='speed' /> Speed<br>
Features:<br>
<input type='checkbox' name='feat1' id='feat1'value='highspeedvpn' /> High Speed VPN <br>
<input type='checkbox' name='feat2' id='feat2' value='transactionguard' />Transaction Guard <br>
<input type='checkbox' name='feat3' id='feat3'value='antivirus' /> Antivirus Addon <br>
<h3 id="generaltext">Fill out your information below:</h3>
<p>
Name:<input name="Name"id='name'size=:50 type="text" required><br>
</p>
<p>
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required><br>
</p>
<p>
Street Address:<input name="S_Address"id='s_address'size=:50 type="text" required><br></p>
<p>
Address 2:<input name="Address_2"id='address_2'size=:50 type="text" required><br></p>
<p>
Zip Code:<input name="Zip"id='zip'size=:50 type="text" required><br>
<p>
City:<input name="City"id='city'size=:50 type="text" required><br>
You can use validation with regular exp -
var email = text_email.value;
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(email)) {
alert("Error msg");
return false;
}
Please see following. You can move validation logic to a different function.
JavaScript:
function checkButons(element) {
...
var emailfield = document.getElementById("emailaddress").value;
var atpos = emailfield.indexOf("#");
var dotpos = emailfield.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailfield.length) {
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
...
}
HTML:
<form action='#' method='post' name='f1' id="VPN" onsubmit='return checkButons(this)'>
....
<p>
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required><br>
</p>
....
</form>
Instead of using <input name="Emailaddress"id='emailaddress'size=:50 type="text" required> use type email, the browser will do the validations for you,but if you want to extra valdiate in server side you could use RegExp for it
Hi check this codepen https://codepen.io/anon/pen/BeeZBv?editors=1111
It is your JS code and it appears to be working, it may not be catching all possible conditions, but it is definitely working. Can you let me know what is not working?
Here is code
<input name="Emailaddress"id='emailaddress'size=:50 type="text" required>
<button onclick="validate()">Click me</button>
function validate() {
var emailfield=document.getElementById("emailaddress").value;
var atpos=emailfield.indexOf("#");
var dotpos=emailfield.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailfield.length){
console.log("Please enter a valid email address with an # and proper domain.")
return false;
}
}
Please keep a submit button on form,as I validated code form is not submitting once you having more input in a form and calling form event onSubmit and form is submitting with one field.
Function checkButons() {
var emailfield = document.getElementById("emailaddress").value;
var atpos = emailfield.indexOf("#");
var dotpos = emailfield.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailfield.length) {
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
}
HTML Code :
<form action='#' method='post' name='f1' id="VPN" onsubmit="checkButons()">
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required>
Street Address:<input name="S_Address"id='s_address'size=:50 type="text" required>
<input type="submit" value="Submit">
</form>
This is my code:
function email() {
var reg = new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam = document.registration.email.value;
var res = nam.match(reg);
if (res) {
alert("enter valid email");
document.registration.email.focus();
} else {
document.registration.password.focus();
}
} else {
document.registration.email.focus();
}
}
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" onblur="email()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
The validation is not working and thus the alert in if condition is not showing. Can anyone help me to achieve this type of validation.
Thanks in advance
Well... Assuming you are trying to do some input validation for your form I suggest reading a bit regarding email validation regex. Then use something like:
https://www.regextester.com/19
Then I think your if statement is flawed. I think you meant that if the email matchs the regular expression if should focus on the password field. if the email is not empty and is invalid if should present an alert. if the email is empty it should focus on the email. I did a quick cleanup and i think the code should look something like(untested code for illustration only):
function validateInput() {
var email= new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var inputValue=document.registration.email.value;
if(inputValue.match(email)) {
document.registration.password.focus();
} else if (inputValue.length > 0) {
alert("enter valid email");
document.registration.email.focus();
} else {
document.registration.email.focus();
}
}
email is a reserved keyword in javascript. first rename your function email to test or whatever you want. second thing you have extra else in your code.
There is a couple errors in your javascript - syntax and dom api.
If you want to do manual validation, here is an example in a fiddle that would work.
https://jsfiddle.net/xb4qrvmy/
function validate_email()
{
var reg=new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam=document.forms["registration"].email.value;
var res=nam.match(reg);
if(!res && nam.length)
{
// I would advice against using alert.
alert("enter valid email");
document.registration.email.focus();
// You want to somehow reset the displaying of the error.
document.forms["registration"].email.value = ''
} else if (res) {
document.registration.password.focus();
}
}
Since You are using html 5 you don't need to write your own validation for email just use
HTML5 has inbuilt validation check for email.
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="email" name="email" placeholder="Email" onblur="email()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
But in case you want to use your function anyways use it as :
<html>
<head>
<script>
function emails()
{
var reg=new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam=document.registration.email.value;
if(!new RegExp(reg).test(nam))
{
alert(document.registration.email);
document.registration.password.focus();
} else {
document.registration.password.focus();
}
}
</script>
</head>
<body>
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" onblur="javascript:emails()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
</body>
function validate()
{
var x = document.forms["myform"]["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>
I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}
I am providing a validation feature on a form for passwords. I need to be able to implement a few validation rules and have them all checked on submit. Now to me the code is sound but I think they may be some logic error in my code that I'm too tired to notice (too the coffee machine!)
Here's the JavaScript:
<script type="text/javascript">
<!--
function validate(registerForm)
registerForm.onsubmit=function()
{
var pw1 = document.forms["register"]["password1"].value;
var pw2 = document.forms["register"]["password2"].value;
//Check values are present in both fields
if(pw1 == '' || pw2 == '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 != pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
//Accept passwords
{
alert("Password accepted!");
return true;
}
}
}
-->
</script>
And the HTML Form to go with it:
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" value="Register" />
</form>
<script type="text/javascript">
<!--
new validate(document.forms['register']);
-->
</script>
Any ideas of lovely StackOverflow community? The exact problem is that it won't check for spaces in passwords or whether two passwords entered are the same. It successfully checks that there is at least something in both password fields.
Thanks Dan
This line:
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
invalid is not defined and I suspect this will cause the problems you're facing.
Made changes to your code got it working http://jsbin.com/igonec/edit#preview
ERRORS
Use of var pw1 = document.forms["register"]["password1"]. It was causing errors
Missing else.
Use of invalid instead of " ".
Wrong use of brackets.
I omitted your errors and made the solution more elegant.
Javascipt
function validate()
{
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
//Check values are present in both fields
if(pw1 ==='' || pw2 === '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.getElementById("password1").value.indexOf(" ") > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 !== pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
else
{
alert("Password accepted!");
return true;
}
}
}
HTML
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" onclick="validate()" value="Register" />
</form>