Jquery Valid() function only apply on 1st element - javascript

I am intend to use javascript to submit the form. Before I want to submit the form, I need to validate my form.
The following is my code :
alert("OP Please edit me to add the validation script code, cdn link or something. Add code that triggers the validation.");
function validateForm1() {
$("#addMapForm").validate();
$('#addMapForm').valid();
console.log($('#addMapForm').valid());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<form enctype="multipart/form-data" action="/Admin/AddMap" method="post" id="addMapForm">
<div>
<br />
<br />
<div class="col-md-12">
<div class="form-group">
<label>Location Name *</label>
<input class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Unit/ Floor Number</label>
<input class="form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Address*</label>
<textarea class="form-control" style="height:100px" required></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Town/ City *</label>
<input class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Zip Code*</label>
<input class="form-control" required/>
</div>
</div>
</div>
</form>

You are missing names on the inputs. A form will only submit named controls and validation plugin won't validate anything without a name
The required fields work fine once you add them
$("#addMapForm").validate();
$("#addMapForm").valid();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<form enctype="multipart/form-data" action="/Admin/AddMap" method="post" id="addMapForm">
<div>
<br />
<br />
<div class="col-md-12">
<div class="form-group">
<label>Location Name *</label>
<input name="location" class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Unit/ Floor Number</label>
<input name="unit" class="form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Address*</label>
<textarea name="address" class="form-control" style="height:100px" required></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Town/ City *</label>
<input name="city" class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Zip Code*</label>
<input name="zip" class="form-control" required/>
</div>
</div>
</div>
<button>Submit</button>
</form>

I assume you are using this: https://jqueryvalidation.org/validate/
Have you implemented the rules of validation for other elements?
rules (default: rules are read from markup (classes, attributes, data))
So either you have those defined in HTML or you need to define them inside validate function called before you called .valid().
Here is an examle:
$("#myform").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
});
In short for more precise help we need all the relevant code or fiddle, plunker a demo showing the example of the problem you are facing.

Try this solution.
$('.form-control').each(function() {
$(this).validate();
$(this).valid();
}

I tried to use the following js to validate all my form, however i know the following code is not the best answer, it only able to show the error message on the first input element.
I am welcome to anyone to post better answer than this.
function validateForm() {
var result = true;
$("#addMapForm").each(function () {
$(this).find(':input').each(function () {
if ($(this).valid() == false) {
result = false;
return;
}
});
});
return result;
}

I gave your form inputs some name attributes. Not sure if you added the actual code to your page, so I did so here. I added a button to trigger just for a demo. I added the simplest bit of CSS.
$("#validateme").on('click', function() {
console.log("validating");
let Validator = $("#addMapForm").validate();
Validator.form();
console.log(Validator.valid());
});
.error { color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
<form enctype="multipart/form-data" action="/Admin/AddMap" method="post" id="addMapForm">
<div>
<br />
<br />
<div class="col-md-12">
<div class="form-group">
<label>Location Name *</label>
<input class="form-control" name="location" required type="text"/>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Unit/ Floor Number</label>
<input class="form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Address*</label>
<textarea class="form-control" name="address" style="height:100px" required></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Town/ City *</label>
<input class="form-control" required type="text"/>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Zip Code*</label>
<input class="form-control" name="zip" required />
</div>
</div>
</div>
<button id="validateme" type="button">Do validate</button>
</form>

Related

Bootstrap validation with JavaScript - disable submission with invalid fields

I have the following HTML code:
<form class="row g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">First name</label>
<input type="text" class="form-control" id="validationCustom01" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="validationCustom02" class="form-label">Last name</label>
<input type="text" class="form-control" id="validationCustom02" value="Otto" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Username</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
<div class="col-md-6">
<label for="validationCustom03" class="form-label">City</label>
<input type="text" class="form-control" id="validationCustom03" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3">
<label for="validationCustom04" class="form-label">State</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>...</option>
</select>
<div class="invalid-feedback">
Please select a valid state.
</div>
</div>
<div class="col-md-3">
<label for="validationCustom05" class="form-label">Zip</label>
<input type="text" class="form-control" id="validationCustom05" required>
<div class="invalid-feedback">
Please provide a valid zip.
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
<div class="invalid-feedback">
You must agree before submitting.
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
With the following JavaScript code, to validate the user input. If there are any invalid fields, it should the user stop submitting his request:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
// putting alert here does not work..?
// something like alert('successfully validated your request!')
}, false)
})
})()
The problem is: I want to alert the user, if the submission was successfully, with the alert() function. But I can't figure out where to put the alert function. I marked the code where I tried putting the alert function into, but it's always triggering even when it's not even validated. Does somebody know what am I doing wrong here? Thank you very much.

page redirect after success bootstrap validation without using php

Team,
I am trying to redirect after success form validation. If it is not success it has to be there in same page if it is success it has to redirect other page
I have added below line after was class validated code
$(location).attr('href', 'data.html');
it is redirecting to next page but I am not seeing any error message I am missing some valdiation.
Here is my entire code.
$(function () {
'use strict'
$('#data_input').on('submit', function (event) {
if (!event.target.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
$(this).addClass('was-validated')
$(location).attr('href', 'data.html');
return true;
});
$("#resetbtn").on("click", function (event) {
event.preventDefault();
$('#data_input')
.trigger("reset")
.removeClass('was-validated')
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<form class="requires-validation" id="data_input" method="post" novalidate>
<div class="form-group row">
<div class="col">
<label> Name</label> <input type="text" class="form-control" name="projectName" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="col">
<label>Code</label> <input type="text" class="form-control" name="projectCode" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<div class="col">
<label>Number</label> <input class="form-control" type="text" name="sprintNumber" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<div class="col"> <label>Start Date:</label> <input type="text" class="form-control has-feedback-left" id="fromdate" placeholder="Please Enter Start Date" name="fromdate" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="col"> <label>End Date:</label> <input type="text" class="form-control has-feedback-left" id="todate" placeholder="Please Enter End Date" name="todate" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<!--<div class="form-group row">
<div class="col">
<label>Total Days</label> <input type="text" class="form-control has-feedback-left"
name="numberdays" id="numberdays" disabled>
</div>
</div>-->
<br />
<button id="submit" type="submit" class="btn btn-primary">Next</button>
<button id="resetbtn" type="button" class="btn btn-secondary">Clear</button>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
Please let me know what I am doing wrong here
in your event submit. You use a validation if statement (checkvalidity).
$('#data_input').on('submit', function (event) {
**if (!event.target.checkValidity()) {**
event.preventDefault()
event.stopPropagation()
}
$(this).addClass('was-validated')
**$(location).attr('href', 'data.html');**
return true; ...
but whether it is valid or not you still perform the location redirect afterwards.
the redirect should be placed in a if instead you will always be redirected before any validation.

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

Why my NgMessages form validation is not behaving like appropriately?

I have written a code which uses Angular JS form validation.
There are two forms,
The first uses form validation
and the second use ng-messages,
The problem is, the second form doesn't seems to work as first one.
In the first form, 3 text fields,
end field has required.
So once I load the page and try to submit the form without filling it,
the error messages appear across the respective fields.
Now if the text field is not empty but has some number validation,
and if I enter text, that only number validation message is shown.
But the same kind for above mentioned validation behavior I am not able to implement in my second form using ng-Messages.
The code is as below,
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>Validator Examples</title>
<script type="text/javascript" src="/home/rahul/Installers/jquery-3.0.0.js"></script>
<script type="text/javascript" src="/home/rahul/Installers/angular.js"></script>
<script type="text/javascript" src="/home/rahul/Installers/Bootstrapv3.0.2/js/bootstrap.js"></script>
<link rel="stylesheet" href="/home/rahul/Installers/Bootstrapv3.0.2/css/bootstrap.css">
<link rel="stylesheet" href="/home/rahul/Installers/Bootstrapv3.0.2/css/bootstrap-theme.css">
<script type="text/javascript">
angular.module("myApp",[]);
angular.module("myApp").controller("myCtrl",myCtrl);
function myCtrl(){
var vm = this;
vm.formOne = {}
vm.formOne.name = "";
vm.formOne.address = "";
vm.formOne.age = 0;
vm.formTwo = {}
vm.formTwo.name = "";
vm.formTwo.address = "";
vm.formTwo.age = 0;
}
</script>
<style type="text/css">
.form-error{
color : red;
}
</style>
</head>
<body ng-controller="myCtrl as vm">
<div class="container">
<div class="page-header">
<h3>Validator Examples</h3>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-2">
<div class="page-header">
<h5><b>ngForm Validator Examples</b></h5>
</div>
<form name="formOne" novalidate>
<div class="form-group">
<input type="text" class="form-control" name="name1" placeholder="Name" required ng-model="vm.formOne.name"
minlength="5" maxlength="10" />
<div ng-show="formOne.$submitted || formOne.name1.$touched">
<div ng-show="formOne.name1.$error.required" class="form-error">Name can't be empty</div>
<div ng-show="formOne.name1.$error.minlength" class="form-error">Name can't be less than 5</div>
<div ng-show="formOne.name1.$error.maxlength" class="form-error">Name can't be more than 10</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="address1" placeholder="Address" ng-model="vm.formOne.address"
required />
<div ng-show="formOne.$submitted || formOne.address1.$touched">
<div ng-show="formOne.address1.$error.required" class="form-error">Address can't be empty</div>
</div>
</div>
<div class="form-group">
<input type="number" class="form-control" name="age1" placeholder="Age" ng-model="vm.formOne.age"
required number/>
<div ng-show="formOne.$submitted || formOne.age1.$touched">
<div ng-show="formOne.age1.$error.required" class="form-error">Age can't be empty</div>
<div ng-show="formOne.age1.$error.number" class="form-error">Age should be numeric</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div><!-- row -->
<div class="row">
<div class="col-md-4 col-md-offset-2">
<div class="page-header">
<h5><b>ngForm ngMessages Validator Examples</b></h5>
</div>
<form name="formTwo" novalidate>
<div class="form-group">
<input type="text" class="form-control" name="name1" placeholder="Name"
ng-model="vm.formTwo.name" required ng-minlength="5" ng-maxlength="10" />
<div ng-messages="formTwo.name1.$error"
ng-show="formTwo.$submitted || formTwo.name1.$touched" class="form-error" role="alert">
<div ng-message="required">Name can't be empty</div>
<div ng-message="minlength">Name can't be less than 5</div>
<div ng-message="maxlength">Name can't be more than 10</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="address1" placeholder="Address" ng-model="vm.formTwo.address"
required />
<div ng-messages="formTwo.address1.$error"
ng-show="formTwo.$submitted || formTwo.address1.$touched" class="form-error">
<div ng-message="required">Name can't be empty</div>
</div>
</div>
<div class="form-group">
<input type="number" class="form-control" name="age1" placeholder="Age" ng-model="vm.formTwo.age"
required number />
<div ng-messages="formTwo.age1.$error" ng-show="formTwo.$submitted || formTwo.age1.$touched"
class="form-error">
<div ng-message="required">Age can't be empty</div>
<div ng-message="number">Age should be numeric</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div><!-- row -->
</div>
</body>
Let me show you the comparison,
in form one the first files validation is like
<form name="formOne" novalidate>
<div class="form-group">
<input type="text" class="form-control" name="name1" placeholder="Name" required ng-model="vm.formOne.name"
minlength="5" maxlength="10" />
<div ng-show="formOne.$submitted || formOne.name1.$touched">
<div ng-show="formOne.name1.$error.required" class="form-error">Name can't be empty</div>
<div ng-show="formOne.name1.$error.minlength" class="form-error">Name can't be less than 5</div>
<div ng-show="formOne.name1.$error.maxlength" class="form-error">Name can't be more than 10</div>
</div>
</div>
And in the form two, the validation is like
<form name="formTwo" novalidate>
<div class="form-group">
<input type="text" class="form-control" name="name1" placeholder="Name"
ng-model="vm.formTwo.name" required ng-minlength="5" ng-maxlength="10" />
<div ng-messages="formTwo.name1.$error"
ng-show="formTwo.$submitted || formTwo.name1.$touched" class="form-error" role="alert">
<div ng-message="required">Name can't be empty</div>
<div ng-message="minlength">Name can't be less than 5</div>
<div ng-message="maxlength">Name can't be more than 10</div>
</div>
In form one, I am able to see only those messages which are invalid,
But in form two I see all the error messages in that field.
You can also see my working code on this like,
FormValidation
Please let me know, were I am going wrong
make sure you have added angular-message.js file in <script>
than Inject ngMessages in module like below
angular.module('myApp', ['ngMessages']);
Write controller alias with form="vm.formTwo" and ng-messages="vm.formTwo....
here is the working example

How to empty ajax loaded form?

How can we empty a ajax loaded form using pure JavaScript or jQuery.
I have tried document.forms[0].reset(); and $('#new-staff-form')[0].reset(); both didn't work it returns undefined.
Update
<div class="box col-md-12 new-staff">
<form id="new-staff-form" method="post">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" name="f_name" placeholder="First name"/>
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" name="l_name" placeholder="Last name"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="user_name">User name</label>
<input id="user_name" type="text" name="user_name" placeholder="User name"/>
</div>
<div class="col-md-6">
<button id="user-avail" class="btn btn-primary">Check available</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary pull-left">Save</button>
</div>
</div>
</form>
</div>
Javascript:
$('#new-item').click(function(){ // works fine until I load new html form using ajax with same ids and class
$('#new-staff-form')[0].reset();
$('.new-staff').slideToggle(); // show new form
});
$('.edit-item').click(function(){ // ajax call this loads everything correctly
var id = $(this).data('staf_id'); //item to delete
$.ajax({
url:url_view_staff+id,
type:'get'
}).done(function(data){
edit_item_id = id;
$('.new-staff').html(data).slideDown();
}).fail(function(data){
$('#errors').html(data.responseText);
$('.valid-error').slideDown();
});
});
JavaScript:
document.getElementById("myForm").reset();
Jquery :
$('#form_id')[0].reset();
Make sure your form id is valid.
FIDDLE
$('#configreset').click(function(){
$('#configform')[0].reset();
});

Categories

Resources