I am trying to make a sign up form with javascript validation but the error message only flashes for a second.
I tried searching other similar questions but I couldn't find the answer...
This is my form code
<form method="post" name="signupForm">
<div id="signup-form" class="col-md-12 col-sm-12 col-xs-12">
<span id="error"></span>
<div class="form-group" id="inputFirst">
<label for="firstname">First Name:</label>
<input class="form-control" type="text" name="first_name" id="firstname" placeholder="John" value="">
</div>
<div class="form-group" id="inputLast">
<label for="lastname">Last Name:</label>
<input class="form-control" type="text" name="last_name" id="lastname" placeholder="Doe" value="">
</div>
<div class="form-group" id="inputEmail">
<label for="signup_email">Email Address:</label>
<input class="form-control" type="email" id="signup_email" name="email" placeholder="example#gmail.com" value="">
</div>
<div class="form-group" id="inputPassword">
<label for="user_password">Password:</label>
<input class="form-control" type="password" id="user_password" name="password" placeholder="Create a Password">
</div>
<button type="submit" onclick="validateForm()" class="btn button">Sign Up</button>
</div>
</form>
And this is my Validation Function
function validateForm() {
var first= document.forms["signupForm"]["firstname"].value;
var last = document.forms["signupForm"]["lastname"].value;
var email= document.forms["signupForm"]["email"].value;
var pass = document.forms["signupForm"]["password"].value;
var msg = "";
var valid= true;
checkname = /[A-z]/;
checkemail= /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if(!/\w/.test(pass))
{
msg="Password can only contain [a-z, A-Z, 0-9, _ (underscore)]";
valid= false;
}
if(!checkemail.test(email))
{
msg="Email address Invalid";
valid= false;
}
if(!checkname.test(first))
{
msg="First and Last Name can only contain alphabets";
valid= false;
}
if(first==="" && last==="" && email==="" && pass==="")
{
msg="Please fill every field given below";
valid= false;
}
document.getElementById("error").innerHTML = msg;
return valid;
}
You should use return validateForm(), this way when the validateForm will return false - it will stop the form from submitting.
function validateForm() {
var first= document.forms["signupForm"]["firstname"].value;
var last = document.forms["signupForm"]["lastname"].value;
var email= document.forms["signupForm"]["email"].value;
var pass = document.forms["signupForm"]["password"].value;
var msg = "";
var valid= true;
debugger;
checkname = /[A-z]/;
checkemail= /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if(!/\w/.test(pass))
{
msg="Password can only contain [a-z, A-Z, 0-9, _ (underscore)]";
valid= false;
}
if(!checkemail.test(email))
{
msg="Email address Invalid";
valid= false;
}
if(!checkname.test(first))
{
msg="First and Last Name can only contain alphabets";
valid= false;
}
if(first==="" && last==="" && email==="" && pass==="")
{
msg="Please fill every field given below";
valid= false;
}
document.getElementById("error").innerHTML = msg;
return valid;
}
<form method="post" name="signupForm">
<div id="signup-form" class="col-md-12 col-sm-12 col-xs-12">
<span id="error"></span>
<div class="form-group" id="inputFirst">
<label for="firstname">First Name:</label>
<input class="form-control" type="text" name="first_name" id="firstname" placeholder="John" value="">
</div>
<div class="form-group" id="inputLast">
<label for="lastname">Last Name:</label>
<input class="form-control" type="text" name="last_name" id="lastname" placeholder="Doe" value="">
</div>
<div class="form-group" id="inputEmail">
<label for="signup_email">Email Address:</label>
<input class="form-control" type="email" id="signup_email" name="email" placeholder="example#gmail.com" value="">
</div>
<div class="form-group" id="inputPassword">
<label for="user_password">Password:</label>
<input class="form-control" type="password" id="user_password" name="password" placeholder="Create a Password">
</div>
<button type="submit" onclick="return validateForm()" class="btn button">Sign Up</button>
</div>
</form>
Your form is probably still be submitting as you are not stopping the form submission. Your event handler is "onClick" on the submit button. This not necessarily stop the form.
You only see the error message for a split second because the page does a full page reload.
Your validation function should be bound to the "onSubmit" event instead.
<form onsubmit="return validateForm();">
Related
I am trying to get the input box border for my name to change to red while displaying a message under neath it when the value is "". I am doing all of this in JavaScript. However, when I test it out, nothing happens. I checked the console and nothing is broken. Was wondering if someone could help me out and see where my error is.
<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">
<h1 style="text-align: center">Billing Address</h1>
<div class="row">
<label for="fname"><i class="fa fa-user"></i> Full Name</label>
<input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
<label for="email"><i class="fa fa-envelope"></i> Email</label>
<input type="text" id="email" name="email" placeholder="john#example.com">
<label for="phone"><i class="fa fa-address-card-o"></i> Phone #</label>
<input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
<label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
<input type="text" id="address" name="address" placeholder="542 W. 15th Street">
<label for="city"><i class="fa fa-institution"></i> City</label>
<input type="text" id="city" name="city" placeholder="New York">
<div class="col-50">
<label for="state">State</label>
<input type="text" id="state" name="state" placeholder="NY">
</div>
<div class="col-50">
<label for="zip">Zip</label>
<input type="text" id="zip" name="zip" placeholder="10001">
</div>
</div>
</form>
<button class="fa orange btn" type="submit" id="customerBtn">Next</button>
<script>
function customerFormValidation() {
reason = "";
reason += validateName(customer_form.firstname);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
function validateName(firstname) {
var error = "";
if (firstname.value == "") {
document.getElementById("firstname").style.display = "block";
document.getElementById("firstname").innerText = "Please enter your name";
document.getElementById("firstname").style.borderColor = "red";
document.getElementById("firstname").focus();
} else {
firstname.style.background = 'White';
document.getElementById('firstname').innerHTML = "";
}
return error;
}
</script>
The problem is that your submit button is outside your form, so it can't trigger the form's submit event.
If you put the button inside the form, it works.
<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">
<h1 style="text-align: center">Billing Address</h1>
<div class="row">
<label for="fname"><i class="fa fa-user"></i> Full Name</label>
<input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
<label for="email"><i class="fa fa-envelope"></i> Email</label>
<input type="text" id="email" name="email" placeholder="john#example.com">
<label for="phone"><i class="fa fa-address-card-o"></i> Phone #</label>
<input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
<label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
<input type="text" id="address" name="address" placeholder="542 W. 15th Street">
<label for="city"><i class="fa fa-institution"></i> City</label>
<input type="text" id="city" name="city" placeholder="New York">
<div class="col-50">
<label for="state">State</label>
<input type="text" id="state" name="state" placeholder="NY">
</div>
<div class="col-50">
<label for="zip">Zip</label>
<input type="text" id="zip" name="zip" placeholder="10001">
</div>
</div>
<button class="fa orange btn" type="submit" id="customerBtn">Next</button>
</form>
<script>
function customerFormValidation() {
reason = "";
reason += validateName(customer_form.firstname);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
function validateName(firstname) {
var error = "";
if (firstname.value == "") {
document.getElementById("firstname").style.display = "block";
document.getElementById("firstname").innerText = "Please enter your name";
document.getElementById("firstname").style.borderColor = "red";
document.getElementById("firstname").focus();
} else {
firstname.style.background = 'White';
document.getElementById('firstname').innerHTML = "";
}
return error;
}
</script>
Regards.
I have textbox and i want to replace the value % of textbox with - on form submit using jquery. But not getting how can i do it.
Here is my HTML
<form [formGroup]="form" id="form" (submit)="addDetails();form.reset()" class="form-style-9" ngNativeValidate>
<div class="form-group">
<div class="col-sm-4">
<label for="username">User Name</label></div>
<div class="col-sm-8"><input type="text" id="username" class="form-control"
placeholder="Please Enter User Name" formControlName="username" required="true">
</div>
<input type="hidden" id="usernameX" name="username" />
</div>
<input type="submit">
</form>
JS
var doReplace = function(string){
return string.replace(/%/g, "-");
}
var $usernameX = $('#usernameX');
$("#form").on("submit", function(e) {
$usernameX.val(doReplace($('#username').val()));
e.preventDefault();
});
You can do it like this. But you don't need jQuery for this:
<form [formGroup]="form" id="form" (submit)="onSubmit()" class="form-style-9" ngNativeValidate>
<div class="form-group">
<div class="col-sm-4">
<label for="username">User Name</label>
</div>
<div class="col-sm-8">
<input type="text" id="username" class="form-control" placeholder="Please Enter User Name" formControlName="username"
required="true">
</div>
<input type="hidden" id="usernameX" name="username" />
</div>
<input type="submit">
</form>
And add a onSubmit() to the component.ts:
public onSubmit(): void {
this.addDetails();
const value = this.form.get('username').value.replace(new RegExp('%'), '-');'
this.form.reset();
}
var myStr = 'replace_underscore_by_minus';
var newStr = myStr.replace(/_/g, "-");
I am creating a multiple section form that needs to validate each section before proceeding to show the next. When I hit continue I want to run a validation that triggers a response on the section above but not the whole form. In addition I want this in one form so that it can be uploaded into IBM forms. I know jQuery is powerful but I don't understand if you can have it all contained in the html.
<script language="JavaScript">
var currentLayer = 'page1';
function showLayer(lyr) {
hideLayer(currentLayer);
document.getElementById(lyr)
.style.visibility = 'visible';
currentLayer = lyr;
}
function hideLayer(lyr) {
document.getElementById(lyr).
style.visibility = 'hidden';
}
function showValues(form) {
var values = '';
var len = form.length - 1;
//Leave off Submit Button
for(i=0; i<len; i++) {
if (form[i].id.indexOf("C") != -1 || // if statement over this one validating visible form elements before continuing
form[i].id.indexOf("B") != -1)
//Skip Continue and Back Buttons
continue;
values += form[i].id;
values += ': ';
values += form[i].value;
values += '\n';
}
alert(values);
}
</script>
</head>
<body>
<div class="container">
<form action="javascript:void(0)" onSubmit="showValues (this)" method="post" enctype="text/plain">
<div id="page1" class="page" style="visibility:visible;">
<label for="firstname">First Name</label>
<input type="text" id="firstname" name="firstname" placeholder="Your first name.." required>
<label for="lastname">Last Name</label>
<input type="text" id="lastname" name="lastname" placeholder="Your last name.." required>
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Your Email.." required>
<label for="phone">Phone</label>
<input type="tel" id="phone" name="phone" placeholder="Your Number.." required>
<center><p><input class="button" type="button" id="C1" value="Continue" onClick="showLayer('page2')"></p></center>
</div>
<!-- First Page Break -->
<div id="page2" class="page">
<label for="title">Title</label>
<input type="text" id="title" name="title" placeholder="Your Title.." required>
<label for="companyname">Company Name</label>
<input type="text" id="companyname" name="companyname" placeholder="Your Company Name.." required>
<input class="button" type="submit" value="Submit">
I have 4 text fields.If I have entered any data in these text fields,these values stored in my database using ajaxcall. I want to know how to validate these fields.My code is not works
$(document).ready(function()
{
function validateform(){
var name=document.regform.emailid.value;
var password=document.regform.passWord.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<form class="text-center" style="width:90%;padding-left:25px" name="regform" onsubmit="return validateform()" >
<div class="form-group">
<input type="text" class="form-control" id="firstName" placeholder="firstName" name="firstName">
</div>
<div class="form-group">
<input type="text" class="form-control" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<input type="text" class="form-control" id="emailid" placeholder="emailid" name="emailid" >
</div>
<div class="form-group">
<input type="text" class="form-control" id="passWord" placeholder="passWord" name="passWord">
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobileNo" placeholder="mobileNo">
</div>
<button type="submit" class="btn btn-success btn-block" id="submitID">SUBMIT</button>
please correct my code?
$.post('url',{'send_post_var':'some_data'},function(result){});
This is some code for a 'Signup' html page; i'm having trouble getting it to check if the two passwords match though. If they don't match, I need a pop up box to display "try again"; if they do math, the page can continue as normal (The sumbit button goes to the home page of my website).
Thanks!!! I've written a javascript function near the bottom....
<form class="form-horizontal" role="form" method="post" action="index.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Create a password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password1" name="password" placeholder="Your Password Here" value="">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Confirm password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password2" name="password" placeholder="Confirm Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="signup" type="submit" value="Sign Up" class="btn btn-primary" onclick="checkPassword()">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
<script>
function checkPassword{
var1 = document.getElementById("password1");
var2 = document.getElementById("password2");
var n = var1.localeCompare(var2)
if(n == 0){
return true;
alert("Passwords do not match, please try again!");
}
return false;
}
</script>
</div>
</div>
</form>
Changed your code slightly:
<form class="form-horizontal" role="form" method="post" onsubmit="return checkPassword();" action="index.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Create a password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password1" name="password" placeholder="Your Password Here" value="">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Confirm password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password2" name="password" placeholder="Confirm Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="signup" type="submit" value="Sign Up" class="btn btn-primary" >
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
</div>
</div>
</form>
<script>
function checkPassword(){
var1 = document.getElementById("password1");
var2 = document.getElementById("password2");
if(var1.value != var2.value){
alert("Passwords do not match, please try again!");
return false;
}
else{
return true;
}
}
</script>
Please note your form tag has onsubmit event, which calls your javascript function(not submit button) this way you stop form from being submited if passwords don't match. Also in your javascript function notice how I display alert before returning false and modified code to compare element values not elements. This code is tested and works.
delete onclick="checkPassword()" from submit tag
and in form tag add
onsubmit="return checkPassword()"
var1 = document.getElementById("password1").value;
var2 = document.getElementById("password2").value;
Also n===0 means, it matches and alert after return statement won't work.
You are comparing the elements, not the values. Get the values from the elements:
var1 = document.getElementById("password1").value;
var2 = document.getElementById("password2").value;
Return false if you want to stop the submission, and show the message before calling return. The localeCompare method returns a non-zero value if the strings are different:
if(n != 0){
alert("Passwords do not match, please try again!");
return false;
}
return true;
Instead of using the click event on the button, use the submit event on the form:
<form class="form-horizontal" role="form" method="post" action="index.php" onsubmit="return checkPassword();">
First switch lines with return and alert.
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
if( pw1 !== pw2 )
{
alert("Passwords do not match, please try again!");
return true;
}
I took the value out of the input elements and compare them with !==. That means, the type of both variables must be equal and the text must also be not equal.