My form validation is not working - javascript

I'm try to validate email and names and what not. I'm using a jquery plugin to try and validate my form. But the thing is that the form does not even go to the javascript, it seems to just reset. Could someone help me?
Here's the html:
<form action method="post" id="register" name="register" class="well form-horizontal">
<label>Username:</label><input type="text" name="username" id="username" />
<label>Email:</label><input type="text" name="email" id="email" />
<label>Password:</label><input type="password" name="password1" id="password1" />
<label>Repeat Password</label><input type="password" name="password2" id="password2" />
<input type="submit" class="btn" value="Submit" />
</form>
Here's my javascript (it's from the jquery plugin):
function myOnComplete () {
alert("does this even work?");
return false;
}
$(document).ready(function() {
$("#register").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Please enter a username.",
"required,email,Please enter your email address.",
"valid_email,email,Please enter a valid email address.",
"required,password1,Please enter a password.",
"custom_alpha,password1,xxxDDD,The first three characters must be numbers, the last three must be letters."
]
});
return true;
});

Related

How to Validate an Email Submission Form When There Are Multiple on the Same Page Using the Same Class?

I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>

What is the best way to do form validation before submitting

Please some one suggest me on,
What is the best way to do form validation before submitting?
Actual scenario is like, i have a button called save,so when user press save button.
I need to validate the data and pass the flow to server to store the data in the tables.
Instead of doing form data validation in server side, is there any possible way to check those in client side itself
<form>
<header>
<h1>Testing </h1>
</header>
<p>
Receipt number:
<input type="text" id="grn" class="tb1" onkeypress="return isNumber(event)" /> Type
<select name="evalu" id="evalu">
<option value="electrical">Electrical</option>
<option value="mechanical">Mechanical</option>
</select>
cad
<select name="cd" id="cd">
<option value="unit1">xv</option>
<option value="unit2">ed</option>
</select>
<input type="button" id="find" value="Find" class="button0" />
<br>
<br> Report No
<input type="text" name="irepno" id="irepno" class="tb1" maxlength="8" /> date
<input type="text" name="idt" id="idt" class="tb1" value="<%= new SimpleDateFormat(" dd-MM-yyyy ").format(new java.util.Date())%>">
<input type="button" id="search" value="Search" class="button0" />
<br></br>
<input type="button" value="Save the record" id="saverecord" class="button0">
</p>
</form>
Javascript itself is developed with an intention to add client side processing of data and validations.
The best way depends on the situation where you are applying and also the
javascript technologies.
If you are not using any specific client side technologies or frameworks for example angularjs or emberjs etc.
You can try using jquery validation plugin
which is avialable ate
https://jqueryvalidation.org/
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
label,
input {
display: block;
}
input{
margin-bottom:15px;
}
label.error {
color: red;
margin-top:-10px;
margin-bottom:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<div class="container">
<h2>Registration</h2>
<form action="" name="registration">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="John" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="Doe" />
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john#doe.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="●●●●●" />
<button type="submit">Register</button>
</form>
</div>
There are many ways to validate a form. I prefer validating a form using HTML elements which is a quick way to check the input details.
Here is a code snippet I used to validate details entered by the client in a simple form.
<fieldset>
<legend>Enter Your Details</legend>
<p>
<label for="fave"> Mobile:
<input maxlength="10" autofocus="on" autocomplete="on" name="mobile" placeholder="Mobile number"/>
</label>
</p>
<p>
<label for="name"> Name:
<input maxlength="30" pattern="^.* .*$" required size="15" name="name" placeholder="Your name"/>
</label>
</p>
<p>
<label for="password"> Password:
<input type="password" required name="password" placeholder="Min 6 characters"/>
</label>
</p>
<p>
<label for="email">
Email: <input type="email" pattern=".*#mydomain.com$" placeholder="user#domain.com" id="email" name="email"/>
</label>
</p>
<p>
<label for="tel">
Tel: <input type="tel" placeholder="(XXX)-XXX-XXXX" id="tel" name="tel"/>
</label>
</p>
<p>
<label for="url">
Your homepage: <input type="url" id="url" name="url"/>
</label>
</p>
</fieldset>
Few elements like
type, maxlength, pattern, required, size
are used for validating a form in client side.
I like the book The Definitive Guide to HTML5, where you can learn to validate a form using front-end development.
Hope this solves your problem.
On form submit, write javascript or jquery script to validate and pass form values to your servlets.
you can use this jquery plugin too.
There are some great validation libraries out there. One I like in particular is jQuery.validate.js as it is well documented and easy to use.
If you would prefer to write your own, a good place to start would be this W3Schools article on Javascript form validation
I suggest you to options, you can choose yourself:
1) Write your validate code inside the function when you click saverecord button.
2) Validate input field (in your case I guess that "Receipt number" and "Report No" is only number), you can write function to handle onkeypress ( or onchange) event to validate which typing from users.

JavaScript link error

I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
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,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>

Have to remove submit button to get js to work

I'm trying to validate login details from an html form. The problem is that the submit button doesn't work with the code. So for example if I leave the username and password blank it won't come up with an alert for "Invalid Username or Password". If I remove type="submit" it works but the button becomes an input text box with an onclick function which does not look good. I was provided with this code as it is a more secure way of passing login details than I had written so I have to confess my ignorance on JS and JSON so apologies if I haven't provided enough info but any guidance would be much appreciated on how to get the button working with the js. This is running on Chrome only. Cheers.
HTML code
<form name="login" id="login-form">
Username<input name="username" id="username" data-bind="value: username" type="text" value="" />
Password<input name="password" id="password" data-bind="value: password" type="password" value="" />
<input name="submit" type="submit" onclick="myApp.getLogin()" value="Login" />
</form>
JS
myApp.getLogin = function(){
var url = "http://localhost:8084/Alumni_JV1/services/login.json?username=" + myApp.vm.username()
+ "&password=" + myApp.vm.password();
console.log(url);
$.getJSON( url, function( data ) {
if(data.response==='success'){
window.location.href="profile.jsp";
}else{
alert("Invalid Username or Password");
}
});
};
A submit button is used to send form data to a server. E.G. <form action='formHandler.php'>. It would submit the form to the current URL if the action attribute isn't defined.
You can get a button without any action with <input type='button' />.
So changing <input type='submit' ... to <input type='button' ... should do the trick :)
Then the code would be:
<form name="login" id="login-form">
Username<input name="username" id="username" data-bind="value: username" type="text" value="" />
Password<input name="password" id="password" data-bind="value: password" type="password" value="" />
<input name="submit" type="button" onclick="myApp.getLogin()" value="Login" />
</form>
Change input type=submit field with button tag.

form validation using java script

Following form validates using JavaScript,but its not working. It still takes action,instead of showing error.I cant figure out what is wrong with code. It seems fine. Can anyone show me my mistakes?
<script type='text/javascript'>
function formValidator(){
var name = document.getElementById('name');
var alpha = /^[a-zA-Z]+$/;
if(!alpha.test.(name.value)){
alert('Please provide a valid name');
name.focus;
return false;
}
var email = document.getElementById('email');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
<div id="contact_form">
<p>Stay Connected.</p>
</div>
<form name="contact" method="post" action="sendmail.php" onsubmit='return formValidator();'>
<fieldset>
<label for="name" id="name_label">Your name *</label>
<input type="text" name="name" id="name" size="50" value="" class="text-input" required />
<label for="email" id="email_label">Your email address *</label>
<input type="text" name="email" id="email" />
<br />
<input type="submit" name="submit" class="button btn btn-primary btn-info" id="submit_btn" value="Send" onclick='Javascript:formValidator();'/>
</fieldset>
</form>
I dont want to use only html5 validation.
This is the error in console
SyntaxError: missing name after . operator
[Break On This Error]
if(!alpha.test.(name.value)){
so use
if (!filter.test(name.value)) instead of if(!alpha.test.(name.value)){
remove .
I guess the if statements are never true, so false is never returned.
replace if (!filter.test.(name.value)) {
to
if (!filter.test(name.value)) {

Categories