I have the following form on my page:
<div class="form-group">
<form class="form-horizontal general subscribe" name="commentform" id="subscribe" method="post" action="#">
<div class="col-lg-8 col-md-8 col-xs-8 lower">
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" />
</div>
<div class="col-lg-4 col-md-4 col-xs-4">
<input type="submit" class="btn btn-fill btn-info form_submit" value="Subscribe"/>
</div>
<div id="form_results"></div>
</form>
</div>
and my jquery code for handling the email stuff is as follows:
jQuery(document).ready(function($) {
"use strict";
$('.form_submit').click(function() {
var form = $(this).parents('form');
$.ajax({
url: 'http://mywebservice/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response) {
output = '<p>Thanks, we will contact you soon!</p>';
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}
});
return false;
});
});
and now the email is added successfuly to the database each time user presses the Subscribe button, but the problem is that the email is not validated with an official email pattern. I thought that in html5 the only necessary check is this <input type="email" but it does not work properly... How can I prevent users from adding wrong email addresses to the database?
You need to add required attribute for a field to be validated
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" required="required" />
If you submit the form using normal submit button then required fields are validated automatically.
If you are submitting or calling javasript function on submit button then
you can use form.checkValidity() to validate the required controls.
jQuery(document).ready(function($) {
"use strict";
$('.form_submit').click(function(){
var form = $(this).parents('form');
form.checkValidity()
$.ajax({
url: 'http://mywebservice/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response)
{
output = '<p>Thanks, we will contact you soon!</p>';
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}
});
return false;
});
});
add required attribute for <input type="email" and sure there is no JavaScript error on the page as well.
You need to add required attribute as per HTML input with type email requires that before it can perform any validation.
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" required />
You can also look into https://jqueryvalidation.org/, I use it and its awesome it allows you show custom message to users
Related
What I want to achieve is: Getting the form validation information from server using an ajax call and show the errors/invalid feedback inside .invalid-feedback with :invalid css applied to the input fields.
<form id="register-form" novalidate>
<div class="form-group">
<label class="sr-only" for="first_name">first name</label>
<input type="text" id="first_name" name="first_name" value="" class="form-control" >
<div class="invalid-feedback"></div>
</div>
....other inputs
</form>
I was able to set the error messages inside the related invalid-feedback using:
$.ajax({
url: actionUrl,
method: "POST",
dataType: "json",
timeout: 5000,
data: form.serialize(),
success: function (response) {
if(response.errors === ''){
pageRedirect("register/login");
} else {
$.each(response.errors, function(field, error) {
form.find('[name="' + field + '"]').siblings('.invalid-feedback').text(error);
});
//feedback is set now how to show them??
}
},
As documented on Bootstrap's Forms documentation here:
Server side
We recommend using client side validation, but in case you require server side, you can indicate invalid and valid form fields with .is-invalid and .is-valid. Note that .invalid-feedback is also supported with these classes.
In short, you need to add the CSS class is-invalid to form controls that have validation errors. When you do this:
the form control will be surrounded with a red-outline to indicate that it has a validation error
sibling divs with the invalid-feedback CSS class will be rendered as red text
Here's a code snippet illustrating this in action with a "mock" response. Try click the Validate button:
var form = $("form").first();
$("#validate").click(function() {
var mockResponse = {
errors :
{
'first_name': 'First name must not be blank',
'last_name': 'Last name must not be blank'
}
};
$.each(mockResponse.errors, function(fieldName, error) {
let field = form.find('[name="' + fieldName + '"]');
field.addClass("is-invalid");
let immediateSibling = field.next();
if (immediateSibling.hasClass('invalid-feedback')) {
immediateSibling.text(error);
} else {
field.after("<div class='invalid-feedback'>" + error + "</div>")
}
});
return false;
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="bg-light">
<div class="container">
<form id="register-form" novalidate>
<div class="form-group">
<label class="sr-only" for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name" value="" placeholder="First Name" class="form-control" >
</div>
<div class="form-group">
<label class="sr-only" for="last_name">Last Name</label>
<input type="text" id="last_name" name="last_name" value="" placeholder="Last Name" class="form-control" >
</div>
<div class="form-group">
<label class="sr-only" for="email">Email Name</label>
<input type="text" id="email" name="email" value="" placeholder="Email" class="form-control" >
</div>
<button id="validate" class="btn btn-primary btn-lg btn-block" type="submit">Validate</button>
</form>
</div>
https://getbootstrap.com/docs/4.5/components/forms/#custom-styles
As you can see, the script shown there doesn't use AJAX at all. Form validation on the client side is done entirely on the client side.
I am building a portfolio website and in the contact form, I want a success/fail response after submission. I prefer to stay on the same page whilst this process.
I tried other solutions that were in other pages related to this topic but I could not understand why they did not work for me. Since I am a newbie, I will appreciate a crystal clear explanation. Thanks a lot!
I tried the solution under this topic: Submit contact form with success/fail alert on same page
MY CURRENT HTML CODE IS;
<form id="contact-form" method="post" action="contact.php" role="form" enctype="text/plain">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Name *" required="required" data-error="name is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="E-mail *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="Subject">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="send a message."></textarea>
<div class="help-block with-errors"></div>
</div>
<input type="submit" name="submit" class="btn btn-send float-" value="Send message">
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
<div class="clearfix"></div>
</form>
I expect to see confirmation or fail report on the same page after submitting the form. It can be anywhere on the page. I just want the visitor to know that I received their message or could not.
Simple example jQuery version:
$("#contact-form").submit(function() {
var name = $("#form_name").val();
var email = $("#form_email").val();
// ...other fields
// and validation if empty or e-mail is valid etc.
// if validation fails just return false;
if( !name ) {
// here You can send message or activate help-block
return false;
}
// if everything correct use for example ajax from jquery
$.ajax({
url: '/url/to/receiver',
type: 'post',
data: { name: name, .... },
dataType: 'jsonp',
success: function( r ) {
if( r.success ) {
// message and pass form validation
// clear fields, or hide contact form
}
if( r.error ) {
// show error
}
}
});
return false;
});
Remember to return from server JSON like { success: true } or { error: true, msg: "message why fails" }.
But it will be much better, when You will change input type=submit to button, and then make:
$("#contact-form .class-of-input-button").off().on('click', function() { /* rest of the code */ });
I am using http://www.formvalidator.net/index.html to validate my form but the form gets submitted even when the validation get failed.
Form code:
<form name="add-todo" class="form-horizontal" action="" method="post">
<h5>Add New Item</h5>
<div class="form-group">
<div class="col-md-12">
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-add">Add</button>
</div>
</div>
</form>
jQuery code:
$(document).ready(function() {
$.validate({
modules: 'security'
});
$('form[name=add-todo]').submit(function(e) {
e.preventDefault();
var text = $("#todo-text-input").val();
$('.btn-add').text('Saving ....');
$.ajax({
url: this.action,
type: this.method,
data: {
text: text
},
success: function(response) {
$("#todo-text-input").empty();
$('.messages').removeClass('hide-element');
$('.alert').addClass('alert-success');
$('.alert').text('To do item added successfully.');
$('.alert').fadeTo(2000, 500).slideUp(500, function() {
$('.alert').slideUp(500);
});
}
});
});
});
dont use submit button. You can use
<button type="button" class="btn btn-primary btn-add">Add</button>
after that check your validation status. if its valid then submit the form.
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
In your input field you don't need to use data-validation="required" just use required like
<input type="text" required class="form-control" id="todo-text-input" name="todo-text">
Please change you form validation code configuration like this:
$.validate({
form : '#registration-form',
modules : 'security',
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
// write your ajax code to submit form data on server
return false; // Will stop the submission of the form
}
});
For more info follow:
http://www.formvalidator.net/index.html#configuration
Because my the totality of my page is a basic "name and email" registration form, I don't see why I can't do a good ole-fashioned
<form action="/Account/Register/" method="POST" id="registration-form">
<fieldset class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="pname" id="name" placeholder="Example input">
</fieldset>
<fieldset class="form-group">
<label for="email">Email Address</label>
<input type="text" class="form-control" name="eaddr" id="email" placeholder="Another input">
</fieldset>
<button class="btn btn-primary" type="submit">Take Survey</button>
</form>
It seems like the definition of overengineering to do
$.ajax({
url : '/Account/Register',
method : 'POST',
data : { pname : $('input[name="pname"]').val(),
eaddr : $('input[name="eaddr"]').val() },
});
After all, that's what a form is for in the first place!
But I do want one thing from the submission of the form and that is success and error callbacks. Is there any way to submit that form in an HTML manner and still hook up callbacks? If so, how?
Use $.submit(), this is the way you can do it with jQuery. As the other commenters wrote, you either post & refresh the page or use ajax:
$("#registration-form").submit(function(){
$.ajax({
url : '/Account/Register',
method : 'POST',
data : { pname : $('input[name="pname"]').val(),
eaddr : $('input[name="eaddr"]').val() },
success: function(data) {},
error: function() {}
});
return false;
});
I'm using Ajax to submit the login form without refreshing the page. I've added a function to see whether the data returns 'error' (which comes up when the user enters an incorrect email/password). If it does not return 'error', the user has been logged in and will be transferred to the page within 2 seconds.
The problem is that my button acts like a double-click button and I cannot see why. This is my JS file:
$(function() {
$("#goLogin").click(function() {
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
});
function finishLogin( data , textStatus ,jqXHR ) {
if ( data == "error" ) {
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
} else {
$('.succesMsg').fadeIn(500).show();
$('.errorMsg').fadeOut(300).hide();
setTimeout("location.href = 'protected.php';",2000);
}
}
I've tried placing it between the document_ready tags, but that isn't working either.
Part of the HTML code:
<div class="login form">
<div class="login-header">Please Login</div>
<form method="post" id="loginForm" name="form">
<label for="email" class="short">Email*</label>
<input type="text" name="email" id="email" class="required" placeholder="" />
<label for="password" class="short">Password *</label>
<input type="password" name="password" id="password" class="required" placeholder="" maxlength="15" />
</form>
<div id="login-functions">
<div class="loginbtn-container">
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Login" />
</div>
<div class="login form actions">
<p class="register account">Register an account</p>
<p class="request password">Lost your password?</p>
</div>
</div>
</div>
<div class="errorMsg">Incorrect. Please recheck your details</div>
<div class="succesMsg"><b>You've been logged in!</b> Please wait while we transfer you</div>
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
did you mean tto hide both? I see the click is working fine, though you should ideally do submit
Take your submit inside the form, and prevent normal form submit using preventDefault()
$("#goLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
Please move your submit button inside the form closing tag first
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Inloggen" />
The above button is placed after the </form> tag.
Because you click on input type submit and progress Ajax on it; it cause submit 2 times.
To avoid it, you can use as Zach Leighton said above ; or use as below
$("#goLogin").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});