I am trying to validate three fields within my form. I have written the code for them and thought they would work. The only problem I'm having is that they're not done in a sequence. If i submit the form without filling in anything, it picks up the email validation.If i fill in the first name, again skips the first name and surname validation and goes straight to email. I tried to make it work in a sequence so first name first then surname and email. Any help would be appreciated.
JS
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
}
function validateForm() {
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
}
function validateForm() {
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
HTML
<form name="buyProductForm" onsubmit="return validateForm()" method="post">
<fieldset id="field1">
<legend>Personal Details</legend>
<label for="name">Firstname:</label>
<input type="text" name="fname" placeholder="Enter your first name" ><br>
<label for="name">Surname:</label>
<input type="text" name="sname" placeholder="Enter your surname"><br>
<label for="email">Email Adress:</label>
<input type="email" name="email" placeholder="Enter your email" ><br>
Jsut create only one validateForm() function and inside this function validate all your fields.
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
<form name="buyProductForm" onsubmit="return validateForm()" method="post">
<fieldset id="field1">
<legend>Personal Details</legend>
<label for="name">Firstname:</label>
<input type="text" name="fname" placeholder="Enter your first name" ><br>
<label for="name">Surname:</label>
<input type="text" name="sname" placeholder="Enter your surname"><br>
<label for="email">Email Adress:</label>
<input type="email" name="email" placeholder="Enter your email" ><br>
<input type="submit" value="Submit">
</form>
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
Related
I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..
My problem is that if I perform validation for the form alone, it performs correctly. But if I write a display function for displaying the details it can't perform the validation. How to do my validation for displaying the details which have been given to the form?
Is what I am giving on submit button correct? Are there any changes? How to declare both functions to perform correctly?
Then I have to do validation when I am displaying details. Please do help me to configure that.
<form name="RegForm" action="/submit.php" method="post">
<p>Name: <input id="name" type="text" size=65 name="Name"> </p><br>
<p>Dob: <input id="dob" type="date"></p><br>
<p> Address: <input id="address" type="text" size=65 name="Address"> </p><br>
<p>E-mail Address: <input id="mail" type="text" size=65 name="EMail"> </p><br>
<p>Password: <input id="pass" type="text" size=65 name="Password"> </p><br>
<p>Telephone: <input id="phone" type="text" size=65 name="Telephone"> </p><br>
<p>Comments: <textarea cols="55" id="Comment" name="Comment"> </textarea></p>
<p><input type="submit" value="send" name="Submit" onclick="Validate(); results(); return false">
</form>
function Validate()
{
var name = document.forms["RegForm"]["Name"];
var email = document.forms["RegForm"]["EMail"];
var phone = document.forms["RegForm"]["Telephone"];
var what = document.forms["RegForm"]["Subject"];
var password = document.forms["RegForm"]["Password"];
var address = document.forms["RegForm"]["Address"];
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (address.value == "")
{
window.alert("Please enter your address.");
name.focus();
return false;
}
if (email.value == "")
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
if (password.value == "")
{
window.alert("Please enter your password");
password.focus();
return flase;
}
if (what.selectedIndex < 1)
{
alert("Please enter your course.");
what.focus();
return false;
}
}
function results()
{
var name=document.getElementById('name').value;
var dob=document.getElementById('dob').value;
var address=document.getElementById('address').value;
var email=document.getElementById('mail').value;
var phone=document.getElementById('phone').value;
document.write("<b>Submitted Successfully!!</b>");
document.write("<b>here is your data.</b><br/>");
document.write("Name :"+name+ " <br/>");
document.write("DateOfBirth :"+dob+ " <br/>");
document.write("Address:"+address+ " <br/>");
document.write("Email :"+email+ " <br/>");
document.write("Telephone: "+phone+ " <br/>");
}
</script>
How to configure this?
I have tried and tried and cannot figure out why when I submit this form it will not activate the javascript function Validate().
This is nearly an exact replica of another form with namely one change: I've added a textarea and removed some check boxes.
I could really use some help troubleshooting this thing...
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate()">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>
function Validate() {
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
There is an exception at the line of code
document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == ""
Dont have any name a7aa41d9-b309-48d7-af97-5a2ce65eb850_First in your document, so that the [0] is undefined.
If you change from
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
to
if (document.getElementsByName('be9953c9-471c-42f4-a1cf-524f5b67fc38_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
The message Please fill out your first name will shown.
You need to prevent the default behavior using e.preventDefault(); otherwise it will try to submit the form
function Validate(e) {
e.preventDefault();
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate(event)">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button type='submit' id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>
i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>
I am adding users to the list using pure js and I am trying to validate the email field using ajax. How to validate the email field before submitting the form? If the email field is valid then i want to submit or else I have show the error in valid email.
Here is the code
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
if you using js then below code will definitely help you.
if (document.getElementById('email').value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(document.getElementById('email').value) == true) {
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
edited code: u have to just replaced it with your code, hope will work for you:
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
Try This
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var EmailmatchArray = email.match(emailPat);
if (EmailmatchArray == null) {
email.focus(); }
else {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
}
return false;
}
DEMO HERE
Try this
It will validate the field , then add the info to list
<form id="myform" onsubmit="return addUser();">
<h2>Add a User:</h2>
<input id="username" type="text" required name="username" placeholder="name">
<input id="email" type="email" required name="email" placeholder="email">
<button type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
DEMO
For the simple validation use the following way (type="email")
<input id="email" type="email" name="email" placeholder="email">
Here is the w3schools link http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validate_email
For Depth use this :
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
//Your Code here
function validateForm()
{
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;
}
}
</form>
Try this
function addUser() {
var email = document.getElementById('email').value;
var username =document.getElementById('username').value;
$.post('/url/to/validation/email/from/db', { "email": email, "username": username }, function(data) {
if(data && data.Success){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
document.getElementById('users').appendChild(entry);
}else{
alert('Email already exists!');
}
},'json');
return false;
}
This will validate the entered email against server and then adds to the list.