How to show the bootstrap 4 validation feedback using jquery? - javascript

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.

Related

Submitting a contact form with sent status on the same page

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 */ });

Form to JSON conversion not working

I am trying to convert a filled in form in the HTML to a JSON request that can then be send to the server over HTTP POST. Although the form is filled, all that i see in the JSON request is an empty JSON array..
JS Snippet is given below
$("#submitSurveyBtn").on("click", function (event) {
event.preventDefault();
var formData = JSON.stringify($("#surveyForm").serializeArray());
console.log(formData);
$.ajax({
type: "POST",
url: "/api/friends",
data: formData,
dataType: "json"
}).then(function (res) {
console.log(res)
});
});
HTML snippet is given below
<form id="surveyForm">
<div class="form-group">
<label for="nameInput">Name(Required)</label>
<input id="name" type="text" class="form-control" id="nameInput" placeholder="name">
</div>
<div class="form-group">
<label for="imgInput">Link to Photo Image (Required)</label>
<input id="imgURL" type="text" class="form-control" id="imgInput" placeholder="http://...">
</div>
codepen - https://codepen.io/rajdhandus/pen/pKWLzR
Your form HTML:
<input id="name" type="text" class="form-control" id="nameInput" placeholder="name">
....
<input id="imgURL" type="text" class="form-control" id="imgInput" placeholder="http://...">
You don't have name of your input so it can not be serialised as it is invalid
change to:
<input id="name" name="name" type="text" class="form-control" id="nameInput" placeholder="name">
...
<input id="imgURL" name="imgURL" type="text" class="form-control" id="imgInput" placeholder="http://...">
That's the main problem you have!
I would prefer to use the following construction, but it's up to you:
$("#surveyForm").on("submit", function (e) {
e.preventDefault();
var formData = $(this).serialize();
// ...
});

html form still showing validation errors even after entering right values with javascript

I have a contact form including validations. Everything is working very well but I have only one issue. An old shown error is not going away when submitting the form another time.
Here is the part of the document I have with the javascript:
<form id="contactForm" th:action="#{/contact}" th:method="POST" entype="utf8" >
<label class="form-control-label on-fonts-style display-7" >Name</label>
<input type="text" value="" class="form-control" placeholder="full name" name="fullName" required="required" >
<label class="form-control-label on-fonts-style display-7" >Email</label>
<input type="email" class="form-control" placeholder="Email Address"
name="email" value="" required="required">
<span id="emailError" style="color:#F41F0E"></span>
<label class="form-control-label on-fonts-style display-7" >Phone</label>
<input type="tel" class="form-control" name="phone" placeholder="phone"
value="">
<label class="form-control-label on-fonts-style display-7" >Message</label>
<textarea type="text" class="form-control" name="message" rows="7">
</textarea>
<span id="messageError" style="color:#F41F0E"></span>
<span id="globalError" class="alert alert-danger col-sm-4"
style="display:none" ></span>
<button type="submit" name="submit" class="btn btn-primary btn-form display-
4">SEND FORM</button>
</form>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script th:inline="javascript">
var serverContext = [[#{/}]];
$(document).ready(function () {
$('form').submit(function(event) {
registerContact(event);
});
});
function registerContact(event){
event.preventDefault();
$(".alert").html("").hide();
$(".error-list").html("");
var formData= $('form').serialize();
$.post(serverContext + "contact",formData ,function(data){
if(data.message == "success"){
window.location.href = serverContext + "successContact.html";
}
})
.fail(function(data) {
if(data.responseJSON.error.indexOf("MailError") > -1)
{
window.location.href = serverContext + "emailError.html";
}
else if(data.responseJSON.error.indexOf("InternalError") > -1){
window.location.href = serverContext + "login?message=" + data.responseJSON.message;
}
else{
var errors = $.parseJSON(data.responseJSON.message);
$.each( errors, function( index,item ){
$("#"+item.field+"Error").show().html(item.defaultMessage);
});
errors = $.parseJSON(data.responseJSON.error);
$.each( errors, function( index,item ){
$("#globalError").show().append(item.defaultMessage+"<br/>");
});
}
});
}
</script>
Let me explain: I have two validations (on message and email), so if I typed them wrong the two errors show up. However if I fixed one of them and submit again the old error is still there. Even if I fix them both and submit the form, the form will be submitted but with still showing the errors.
Please anyone have a solution for this problem?
Add a class for all the error spans called error as an example.
when you get to the error checking part you can first hide all errors
$(".error").hide()
and then carry on with the validation as normal :)

Why is my email validation not working in bootstrap and html5?

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

Form data sent dynamically through json to server not working?

Script code:
function submitdata(){
alert("hi");
//var formRequest = JSON.stringify($("#submitdatafrm").serializeArray());
var test = JSON.stringify({
"firstName": $('#fname'),
"email":$('#email'),
});
console.log(test);
$.ajax({
type: "POST",
contentType: 'application/json',
url: "http://localhost:8080/formdataserver/rest/reqdemo/add",
data: test ,
dataType:"text",
success:successmethod,
error: function(data,status) {
alert("Error "+status);
}
});
}
function successmethod(data){
alert("sucess")
}
Html code:
<form class="form-horizontal" id="submitdatafrm">
<div class="form-group">
<label class="col-md-4 control-label" for="fname">First Name</label>
<div class="col-md-6"><input id="fname" name="fname" type="text" placeholder="First Name" class="form-control input-md"></div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email</label>
<div class="col-md-6"><input id="email" name="email" type="email" placeholder="Email" class="form-control input-md"></div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="button"></label>
<div class="col-md-4">Request a demo now</div>
</div>
</fieldset>
</form>
In the above code when i pass values through json statically(hardcoded values) it is working fine and values are stored in database.but when i pass the values dynamically(dynamic values through form) the values are not passed and showing an error alert message??what is the wrong am doing in the json code??Any help would be Appreciated...
How to send a whole form:
The following is sufficient to send all values in the form:
data: $('#submitdatafrm').serialize()
Is there a particular reason you need to send as JSON? This should convert the name/values to JSON:
data: JSON.stringify($('#submitdatafrm').serialize())
Note: You need to ensure your target URL is on the same website to avoid cross-site issues (why do you have an absolute URL?).
Your sample data uses firstname but the input is called fname, so it may just be a typo, but without server code that is hard to see :)
Whats in a name?
From your class code I see that the server expects a value of firstName, so if you want to simply serialize the form you will need to have name="firstname" (not fname):
<input id="fname" name="firstname" type="text" placeholder="First Name" class="form-control input-md">
Test sample needs val():
As CBroe mentioned in comment, your sample code is not actually sending the values of the fields, but instead the entire jQuery object. It should have been:
var test = JSON.stringify({
"firstName": $('#fname').val(),
"email": $('#email').val(),
});

Categories