jQuery validation does not validate my textarea element - javascript

I am currently using jQuery validation to validate my fields. I've two fields,
named "comments" & "account name". Both fields have the same rule method where required is true. When I click the "save" button, only the account name was validated. Why is that so? Here is a screenshot of my problem and my codes
$(document).ready(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
},
});
$('#dataForm').validate({
rules: {
commentInput: {
required: true
},
accountNameInput: {
required: true
}
},
submitHandler: function(form) {
alert('success');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">
<div class="form-group">
<label class="control-label" for="commentInput">Comments</label>
<textarea class="commentInput" id="commentInput" cols="20" rows="5"></textarea>
</div>
<div class="form-group">
<label class="control-label" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
</div>
<input type="submit" class="btn btn-primary" value="Save" id="saveButton" />
</form>

You have to give all form fields that need validation a name attribute. That's where the validation plugin gets the reference to the element from.
From the documentation:
Throughout the documentation, two terms are used very often, so it's
important that you know their meaning in the context of the validation
plugin:
method: A validation method implements the logic to validate an element, like an email method that checks for the right format of a
text input's value. A set of standard methods is available, and it is
easy to write your own.
rule: A validation rule associates an element with a validation method, like "validate input with name "primary-mail" with
methods "required" and "email".
The name attribute is also required to be present on any form field that will need to transmit its data as part of the form submission.
$(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
},
});
$('#dataForm').validate({
rules: {
commentInput: {
required: true
},
accountNameInput: {
required: true
}
},
submitHandler: function(form) {
alert('success');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">
<div class="form-group">
<label class="control-label" for="commentInput">Comments</label>
<textarea class="commentInput" id="commentInput" name="commentInput" cols="20" rows="5"></textarea>
</div>
<div class="form-group">
<label class="control-label" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
</div>
<input type="submit" class="btn btn-primary" value="Save" id="saveButton" />
</form>

The validation plugin targets by the name attribute:
<textarea id="commentInput" name="commentInput" cols="20" rows="5"></textarea>

You need use the name attribute for validate.
$(document).ready(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
},
});
$('#dataForm').validate({
rules: {
commentInput: {
required: true
},
accountNameInput: {
required: true
}
},
submitHandler: function(form) {
alert('success');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">
<div class="form-group">
<label class="control-label" for="commentInput">Comments</label>
<textarea name="commentInput" class="commentInput" id="commentInput" cols="20" rows="5"></textarea>
</div>
<div class="form-group">
<label class="control-label" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
</div>
<input type="submit" class="btn btn-primary" value="Save" id="saveButton" />
</form>

Related

Error Placement Issue for the required fields

I have an issue with error placement for the required field and it overlaps exactly on the labels of the field and I'm using bootstrap modal with class form-label-group and it works fine if I remove the class. I want to show the error messages within the span of each input fields. It's really hard for the users to check the field names when I validate the form before submit.
$('#Test').validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
FName: {
required: true
},
LName: {
required: true
}
},
invalidHandler: function(event, validator) { //display error alert on form submit
},
highlight: function(element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
success: function(label) {
label.closest('.form-group').removeClass('has-error');
label.remove();
},
errorPlacement: function(error, element) {
if (element.closest('.input-icon').length === 1) {
error.insertAfter(element.parent("span"));
} else {
error.insertAfter(element.parent("span"));
}
},
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Test" action="#" class="addForm floating-labels m-t-40">
<div class="row">
<div class="col-md-3 col-lg-3 col-3">
<div class="form-group">
<input type="text" id="FName" name="FName" value="" class="form-control" required="required" autofocus="autofocus" maxlength="50">
<span class="bar"></span>
<label for="FName">First Name*</label>
</div>
</div>
<div class="col-md-3 col-lg-3 col-3">
<div class="form-group">
<input type="text" id="LName" name="LName" value="" class="form-control" required="required" autofocus="autofocus" maxlength="50">
<span class="bar"></span>
<label for="LName">Last Name*</label>
</div>
</div>
</div>
</div>
Thanks Swati and it worked. The issue was in one of my class, which was causing the issue.
element.parent("span") to element.next("span")

Bootstrap form validation in jQuery instead of plain JavaScript?

I found this on Bootstrap to use Bootstrap form validation. Why is the example in plain JavaScript instead of jQuery when the rest of Bootstrap scripts are in jQuery?
How can this be done with jQuery?
https://getbootstrap.com/docs/4.0/components/forms/#validation
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap 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);
})();
</script>
use Jquery Validation : https://jqueryvalidation.org/documentation/
$(document).ready(function(){
$('#contact-form').validate({
rules: {
'checkbox': {
required: true
}
},
highlight: function (input) {
$(input).addClass('is-invalid');
},
unhighlight: function (input) {
$(input).removeClass('is-invalid');
},
errorPlacement: function (error, element) {
$(element).next().append(error);
}
});
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<form id="contact-form" method="POST" action="/contact">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Name" id="name" class="form-control" autocomplete='name' value="" required>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" id="email" class="form-control" autocomplete='email' value="" required>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="phone" placeholder="Phone" id="phone" class="form-control" autocomplete='tel' value="" required>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<textarea placeholder="Message" class="form-control" name="message" rows="5" class="form-control" required></textarea>
<div class="invalid-feedback"></div>
</div>
<div class="container-contact-form-btn">
<button class="btn btn-primary" type="submit">
Send Now
</button>
</div>
</form>
$(document).ready(function(){
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
$(this).addClass('was-validated');
});
});
This example was most likely written in JS as that's what the author of the Bootstrap documentation was most comfortable with. You can convert it to jQuery like this:
(function() {
'use strict';
$(window).on('load', function() {
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
$(this).addClass('was-validated');
});
});
})();

jQuery Validate not validating on form submit

I'm facing some problems with jQuery Validate. I've already put the rules but when i'm submitting the form, nothing happens.
I'm using ASP.NET MVC 4 and Visual Studio 2010.
EDIT: Click here to see my entire code. I'm trying to post it here but i'm getting the following error: 403 Forbidden: IPS signature match. Below is part of my code with Andrei Dvoynos's suggestion. I'm getting the same error. Clicking on submit and the page being reloaded
#{
ViewBag.Title = "Index";
}
#section Teste1{
<script type="text/javascript">
$(document).ready(function () {
$("#moeda").maskMoney();
$("#percent").maskMoney();
$(":input").inputmask();
$('#tel').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.inputmask({ "mask": "(99) 99999-999[9]" });
} else {
element.inputmask({ "mask": "(99) 9999-9999[9]" });
}
}).trigger('focusout');
//the code suggested by Andrei Dvoynos, i've tried but it's occurring the same.
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});
});
</script>
}
#using (#Html.BeginForm("", "", FormMethod.Post,
new { id = "form1", name = "form1" }))
{
<fieldset>
<legend>Sign In</legend>
<div class="form-group" id="divCpf">
<label for="cpf">CPF</label>
<input data-inputmask="'mask': '999.999.999-99'" class="form-control" id="cpf" />
</div>
<div class="form-group" id="divCep">
<label for="cep">CEP</label>
<input data-inputmask="'mask' : '99999-999'" type="text" class="form-control" id="cep" placeholder="CEP" />
</div>
<div class="form-group" id="divTel">
<label for="tel">Telefone</label>
<input type="text" class="form-control" id="tel" placeholder="tel" />
</div>
<div class="form-group" id="email">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" />
</div>
<div class="form-group" id="divcnpj">
<label for="cnpj">CNPJ</label>
<input data-inputmask="'mask' : '99.999.999/9999-99'" type="text" class="form-control" id="cnpj" placeholder="CNPJ" />
</div>
<div class="form-group">
<label for="moeda">Moeda</label>
<input type="text" id="moeda" data-allow-zero="true" class="form-control" />
</div>
<div class="form-group">
<label for="Percent">Percent</label>
<input type="text" id="percent" data-suffix="%" data-allow-zero="true" class="form-control" maxlength="7" />
</div>
<input type="submit" class="btn btn-default" value="Sign In" id="sign" />
</fieldset>
}
My tests (all unsuccessful):
1 - put the $("form").validate() into $(document).ready()
2 - put the required class on the fields.
jQuery Validate plugin version: 1.13.0
In addition to the fatal problem you fixed thanks to #Andrei, you also have one more fatal flaw. The name attribute is missing from your inputs.
Every element must contain a unique name attribute. This is a requirement of the plugin because it's how it keeps track of every input.
The name is the target for declaring rules inside of the rules option.
$("#form1").validate({
rules: { // <- all rule declarations must be contained within 'rules' option
cpf: { // <- this is the NAME attribute
required: true,
....
DEMO: http://jsfiddle.net/3tLzh/
You're missing the rules property when calling the validate function, try something like this:
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});

jQuery Validation Plugin Not Work With Jquery Form Plugin

I work with jquery validation plugin for validate my form. in my form I have jquery upload file using jquery form plugin.
JS:
$(document).ready(function()
{
$("#fileuploader").uploadFile({
url: "upload.php",
dragDrop:true,
multiple:false,
fileName: "myfile",
returnType:"json",
showDelete:true,
showFileCounter:false,
onSuccess:function(fileArray, data, xhr, pd)
{
var url = "download.php?filename="+data[0];
//pd.filename.html(data[0]);
pd.filename.html("<a href='"+url+"'>"+data[0]+"</a>");
},
deleteCallback: function(data,pd)
{
for(var i=0;i<data.length;i++)
{
$.post("delete.php",{op:"delete",name:data[i]},
function(resp, textStatus, jqXHR)
{
//Show Message
alert("File Deleted");
});
}
pd.statusbar.hide(); //You choice to hide/not.
}
});
});
$('form').validate({
ignore:'.uploadFile',
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
HTML:
<form>
<div id="fileuploader">Upload</div>
<div class="form-group">
<label class="control-label" for="firstname">Nome:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input class="form-control" placeholder="Insira o seu nome próprio" name="firstname" type="text" />
</div>
</div>
<div class="form-group">
<label class="control-label" for="lastname">Apelido:</label>
<div class="input-group">
<span class="input-group-addon">€</span>
<input class="form-control" placeholder="Insira o seu apelido" name="lastname" type="text" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Now, jquery validation is a conflict with jquery form plugin and not validate my form. I tried ignore:'.uploadFile' function but jquery validation not work.
How can I fix this problem?!
Not Work DEMO : http://jsfiddle.net/hTPY7/1400/
Worked Demo without upload plugin: http://jsfiddle.net/hTPY7/1404/

Conditional validation with BootstrapValidator

I'm using BootstrapValidator plugin to validate a form, however i have following problem. I have a "Phone" field and a "Mobile" field if the user does not enter either of them, I wanted to launch a custom message (you need to inform one phone number), and if he inform any (phone or mobile) validation would be satisfied.
The doubt is: Is it possible to use conditional inside BootstrapValidator?
This seems to be working for a lot of people derived from this post:
$('form').validate({
rules: {
Phone: {
required: true
},
Mobile: {
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
and the html:
<form>
<div class="form-group">
<label class="control-label" for="Phone">Phone:</label>
<div class="input-group">
<input class="form-control" name="Phone" type="text" />
</div>
</div>
<div class="form-group">
<label class="control-label" for="Mobile">Mobile:</label>
<div class="input-group">
<input class="form-control" name="Mobile" type="text" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

Categories

Resources