Bootstrap validation not working despite including script and following docs - javascript

I can't get my form to validate despite having the script both on the page and in my boilerplate layout. I have tried moving the tags around to different places but the server-side validation is the only part working.. the form won't run the client side validation.
<% layout('layouts/boilerplate') %>
<div class="row">
<h1 class="text-center">Create Artist Profile</h1>
<div class="col-6 offset-3">
<form action="/artists/new" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label" for="email">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="name#domain.com" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label for="formFile" class="form-label">Upload band photo</label>
<input class="form-control" type="file" id="image" name="image" multiple="false">
</div>
<div class="mb-3">
<button class="btn btn-success">Create Profile</button>
</div>
All artists
</form>
</div>
</div>
Here's the script tag from the body of my layouts/boilerplate.ejs
<script>
(function () {
'use strict'
bsCustomFileInput.init()
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.validated-form')
// Loop over them and prevent submission
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})
</script>
Any ideas what I'm doing wrong with this form?

have you tried changing the form class to "needs-validation"?
also try this code
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.querySelectorAll('.validated-form')
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();

Related

Bootstrap 5 form validation doesn't fire

I have a form for allowing the user to change their account password, like so:
<div class="signup-form-small">
<form method="post" name="frmPassword" id="frmPassword" class="needs-validation" novalidate>
<div class="form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="curpwd" name="curpwd" required>
<label class="form-label" for="curpwd">Your Current Password</label>
</div>
</div>
<div class="form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="newpwd" name="newpwd" required>
<label class="form-label" for="newpwd">Enter New Password</label>
</div>
</div>
<div class="row form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="cnfpwd" name="cnfpwd" required>
<label class="form-label" for="cnfpwd">Confirm New Password</label>
</div>
</div>
<div class="form-group">
<button type="submit" id="btnPwdSubmit" name="btnPwdSubmit" class="btn btn-primary btn-lg btn-block w-100 has-spinner">
<div class="spinner-border float-right hidden" id="pwdspinner" role="status"></div>
Change My Password
</button>
</div>
</form>
</div>
In my script I have the following code block which should universally handle validation:
$(document).ready(function () {
'use strict';
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
});
and finally, here is the script code that fires when the user clicks the 'Chnage My Password' button in the form:
$('#frmPassword').submit(function (event) {
event.preventDefault();
setPwdDisabled();
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1) {
obj.Is_Body_HTML = true;
}
else {
obj.Is_Body_HTML = false;
}
if (obj.Is_Active == 1) {
obj.Is_Active = true;
}
else {
obj.Is_Active = false;
}
if ($('#curpwd').val() != $('#cnfpwd').val()) {
$('toastPwd').toast('show)');
return;
}
var json = JSON.stringify(obj);
var request = $.ajax({
url: "../handlers/changepwd.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#spnPwdErr').html(msg.Status);
$('#toastPwdFail').toast('show');
}
else
$('#toastPwdSuccess').toast('show');
});
request.fail(function (jqXHR, textStatus) {
$('#spnPwdErr').html('Unable to complete your request at this time.');
$('#toastPwdFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setPwdEnabled();
});
});
For whatever reason, the form validation never fires, and I don't know why. I added alerts into the validation code and they never pop up. The form submission happens no matter what. I don't get any errors or other messages in the console. Can anyone shed any light on why this is not functioning?
Remove the add event listener - having it inside the jquery ready makes it redundant -
$(document).ready(function () {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
});

Form validation with Ajax call triggers when not validation

I have a simple form with Ajax call, but ajax call gets executed even if form is not validated.
In below code line console.log("This line should execute only if Form is validated"); gets executed when form is not validate.
Bootstrap 5 validation Codepen code
(function () {
"use strict";
const forms = document.querySelectorAll(".requires-validation");
Array.from(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
else
{
console.log("This line should execute only if Form is validated");
// Call Ajax Function
// AjaxCallSaveData();
}
form.classList.add("was-validated");
},
false
);
});
})();
//$(document).ready(function () {
function AjaxCallSaveData()
{
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
superheroAlias: $("#superheroAlias").val()
};
$.ajax({
type: "POST",
url: "SubmitFORM.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
}
//});
Not sure if i am doing it right?
HTML
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<h3>Register you interest</h3>
<p>Fill in the data below, we will get back to you!</p>
<form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" id="name" placeholder="Full Name" required>
<div class="valid-feedback">Username field is valid!</div>
<div class="invalid-feedback">Username field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input class="form-control" type="email" name="email" id="email" placeholder="E-mail Address" required>
<div class="valid-feedback">Email field is valid!</div>
<div class="invalid-feedback">Email field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
event.preventDefault() will only stop the form from submitting. It cannot stop next lines of the JavaScript function from executing.
You should use return in place of event.preventDefault().

Used bootstrap for validating the form ,even there is some validation the form is getting submitted.How should I avoid it

I am using the bootstrap 'needs-validation' for checking the validation form. Here when I click the submit button its validating the field and form is also getting submitted. What I want is when the validation fails the form should not get submitted. I found the form validation from (needs validation) from here https://www.w3schools.com/bootstrap4/bootstrap_forms.asp and I used it in my program.
My script is
<div class="row top-space-30">
<form class="needs-validation" novalidate action="" method="">
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="studentname">Student Name:</label>
<div class="col-md-6">
<input id="role" name="studentname" type="text" placeholder="name" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="department">Department:</label>
<div class="col-md-8">
<input class="form-control" type="text" id="department">
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
<script>
// Disable form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
$("#submit").click(function (e) {
var studentName = $("#role").val();
var departmentsList = $("#department").val().split(',');
$.ajax({
type: 'POST',
url: '/students/add',
data: {
'role': studentName,
'departmentslist': JSON.stringify(departmentsList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
})
</script>
Try this one, I have one function for validationsformSubmit add your own validations in that function.
<div class="row top-space-30">
<form class="needs-validation" name="myForm" action="" method="" onsubmit=" return formSubmit()" >
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="studentname">Student Name:</label>
<div class="col-md-6">
<input id="role" name="studentname" type="text" placeholder="name" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="department">Department:</label>
<div class="col-md-8">
<input class="form-control" type="text" name = "departmentname" id="department">
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="Submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
//Disable form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
function formSubmit(){
var forms = document.forms["myForm"];
var studenName = forms.studentname.value;
var departmentName = forms.departmentname.value;
// perform validation for studentname and departname if they are validated then return true, else for wrong input return false
if(isNaN(studentname) && isNaN(departmentname)){
return true;
}
else{
return false;
}
}
$("#submit").click(function (e) {
var studentName = $("#role").val();
var departmentsList = $("#department").val().split(',');
$.ajax({
type: 'POST',
url: '/students/add',
data: {
'role': studentName,
'departmentslist': JSON.stringify(departmentsList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
})
</script>

Angular - $scope.myForm.$setPristine() is undefined

Form is not cleared after saved record in angularJs. I'm trying to reset form many ways, but form is not reset.
My angularjs version is 1.4.8.
This question is also a duplicate, but I tried what stack overflow users said. That has not worked for me.
Looking for a positive reply
Thank you.
Html code:
<form name="myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue"
id="forumValue" placeholder="fourm Id" />
<div class="form-group row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="answer" class="form-control"
ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success"
ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
Controller Code:
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};
Is your form wrapped in an ng-if statement? If so, the form might be inside a child scope, and you might try:
Option A
Replace your ng-if with an ng-hide.
Option B
Bind the form to an existing object on the parent scope:
$scope.myData = {};
$scope.saveUserAnswer = function(fid) {
...
};
Then in your HTML, refer to the form on the parent scope:
<form name="myData.myForm" id="myForm" novalidate>
</form>
Source: https://github.com/angular/angular.js/issues/15615
I have attempted to recreate your problem but without the call to the UserRepository just to confirm that we can set the form $pristine value to true and to reset the form.
<form name="form.myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue" id="forumValue" placeholder="fourm Id" />
<div class="form-grou`enter code here`p row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="form.myForm.answer" class="form-control" ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success" ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
<pre>{{form.myForm.$pristine}}</pre>
and the controller code like so :
$scope.form = {};
$scope.saveUserAnswer = function(fid) {
$scope.form.myForm.$setPristine();
$scope.fid = {};
//omitted the user repository code
};
The above will set the pristine value of the form to true and also reset the value of fid on click of the button.
EDIT
Also the call to your repository function should be in this format:
UserRepository.saveUserAnswer(fid).then(
function(response){
//success
},
function(response){
//error
}
);
In controller try to add '$scope.fid.answer=null;' after scope.myForm.$setPristine();
like this.
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.fid.answer=null;
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};

HTML Form onsubmit not executing the external function

I have a HTML Form and on submit, a validate() function to be called.
The submit works fine, if the validate() function is within the "script" tag at the end of the "body" tag.
Otherwise, the submit doesn't call the validate() function when it is present in external js file, even though document.ready is used, as in https://jsfiddle.net/vg47127o/1/
HTML --
<form method="post" action="#" onsubmit="return validate()" name="loginForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="error-block"><span class="glyphicon glyphicon-exclamation-sign"> </span> <span class="error-msg"></span></p>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="username">username:
</label>
<div class="col-sm-9">
<input type="text" class="form-control digits-only" id="username" placeholder="Enter Username">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-9">
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="loginBtn" class="btn btn-default">Log In</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
SCRIPT --
$(document).ready(function() {
var displayError = function(error, msg) {
$(".error-block .error-msg").text(msg);
if (error === true)
$(".error-block").show();
else
$(".error-block").hide();
return true;
};
//Validating the input fields
var validate = function() {
var $username = $("#username").val(),
$password = $("#password").val();
if ($username === '' || $password === '') {
displayError(true, ' Username or Password cannot be empty. ');
return false;
} else if ($username.length < 6 || $password.length < 6) {
displayError(true, ' Username and Password should be a minimum of 6 characters. ');
return false;
} else {
displayError(false, ' ');
return true;
}
};
});
Am I missing out something here or What could be the reason for this.
Here's an updated fiddle that is working. You need to trap the submit() event if validate does not return true.
This is what you would include in your jQuery:
$("form").on("submit", function (event) {
if (!validate()) {
event.preventDefault();
}
});
Then your <form> tag would simply be <form method="post" action="#" name="loginForm" class="form-horizontal" role="form">
FYI
The reason for this is that when your validate() function is inside of your document ready, it is scoped to the document ready function, therefore, inline DOM event triggers do not have access to it. You have to set up the event handler inside the jQuery function, or declare your validate() function outside of your document ready function.
The validate variable is scoped to the anonymous function you put into $(document).ready. That means it can be accessed only from within that function and not from the page which lives in the global scope.
Add the event listener using the $(...).submit function instead:
$(document).ready(function() {
/* *** */
//Validating the input fields
$("[name=loginForm]").submit(function() {
var $username = $("#username").val(),
$password = $("#password").val();
/* *** */
});
});

Categories