Error Placement Issue for the required fields - javascript

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")

Related

jQuery validation does not validate my textarea element

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>

jquery validation with php form

I am trying to use jquery validation for a php form to change your password but I keep getting the error "Your password must be the same as above" when the password is correct. I can't seem to find out where I have went wrong at all... Here's the JS code
var changepassword = function() {
return {
init: function() {
/*
* Jquery Validation, https://github.com/jzaefferer/jquery-validation
*/
$('#changepassword').validate({
errorClass: 'help-block animation-slideUp',
errorElement: 'div',
errorPlacement: function(error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function(e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function(e) {
if (e.closest('.form-group').find('.help-block').length === 2) {
e.closest('.help-block').remove();
} else {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
}
},
rules: {
'newpassword': {
required: true,
minlength: 6
},
'newpassword-verify': {
equalTo: '#newpassword',
required: true
}
},
messages: {
'newpassword': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long'
},
'newpassword-verify': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long',
equalTo: 'Please enter the same password as above'
}
}
});
}
};
}();
This is the PHP/HTML for the form
<form method="POST" class="form-horizontal form-bordered" id="changepassword">
<div class="form-group">
<label class="col-md-3 control-label" for="newpassword">New Password</label>
<div class="col-md-6">
<input type="password" id="newpassword" name="newpassword" class="form-control" placeholder="New Password" required>
</div>
</div>
<!-- This is where I keep getting the error -->
<div class="form-group">
<label class="col-md-3 control-label">Repeat Password</label>
<div class="col-md-6">
<input type="password" id="newpassword-verify" name="newpassword-verify" class="form-control" placeholder="Repeat Password" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="oldpassword">Current Password</label>
<div class="col-md-6">
<input type="password" id="oldpassword" name="oldpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group form-actions">
<button type="submit" name="update" class="btn btn-block btn-primary">Update</button>
</div>
</form>
Sorry, I was able to fix it by making a new file called settings1.php then removing the old one and renaming the new one with the old name.

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>

".errorClass" of jQuery validate works but the class cannot be found by "hasClass()"

Problem
I'm not a programmer and I'm trying to do some programming.
I tried to use jQuery-validate plug-in to control the form input, it works perfectly, Bootstrap can even find the ".text-danger" class and change its' color.
However, the ".hasClass()" method just can't.
I put some "console.log()" functions in the for loops which are used to find this class.
The log messages I received every time are "changed", "hasSmall", "noClass".
Have I made mistakes in the JS code?
Please help me out.
Code
This is within my HTML form:
<div class="form-group">
<label for="username">Username </label>
<input type="text" class="form-control" name="username" id="signUpUserName" />
</div>
<div class="form-group">
<label for="password">Password </label>
<input type="password" class="form-control" name="password" id="signUpPassword" />
</div>
<div class="form-group">
<label for="email">Email </label>
<input type="text" class="form-control" name="email" id="signUpEmail" />
</div>
This is the JavaScript:
errorPlacement: function(error, element) {
var obj = $('[name="'+element.attr('name')+'"]');
obj.siblings('label').append(error);
},
I have changed some values in the valadate.min.js:
$.extend($.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "text-danger", // I've changed this
validClass: "text-success", // this
errorElement: "small", // and this
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
Also, JS:
function changeInputAreaStatus(id) {
$(id).change(function(id) {
console.log('changed');
var errorMessageContainer = $(id).siblings('label');
if(errorMessageContainer.has('small')){
console.log('hasSmall');
if (errorMessageContainer.children('small').hasClass('text-danger')) {
console.log('hasDangerClass');
errorMessageContainer.parent().removeClass('has-error').addClass('has-error');
} else if (errorMessageContainer.children('small').hasClass('text-success')) {
console.log('hasSucessClass');
errorMessageContainer.parent().removeClass('has-error');
} else {
console.log('noClass');
}
}
});
}
changeInputAreaStatus('#signUpUserName');
changeInputAreaStatus('#signUpPassword');
changeInputAreaStatus('#signUpEmail');
You should try something like this :
var textSuccess = errorMessageContainer.find('.text-success');
if(textSuccess != null && textSuccess.length > 0){
console.log('hasSucessClass');
}
it should help you to verify if errorMessageContainer has a text-success class.
Best regards

jQuery Validation Plugin - Form does not submit

I'm using the jQuery Validation Plugin, and I have a problem.
Both my jQuery and HTML is perfectly valid (according to JSLint and the WC3 Markup Validation Service), but when I hit the submit button, nothing happens.
My code even clearly states that, upon submitting, an alert should pop up, but even that doesn't work. The form is however validated correctly, and in the and, all fields are green (meaning they passed validation) but it doesn't actually submit (nothing happens).
Also, in my DevTools, the console does not report any errors.
Possibly/probably relevant; the email-textfield and the username-textfield are both being checked by a remote PHP script. This script works, strange enough, only after the second time. So when I first leave (blur) the email-textfield, nothing happens, it's isn't marked correct nor false.
Only when I (re-enter and) leave the textfield for the second time, it is validated, or when I hit the submit button. (This shows the submit button is actually connected, it just simply does not submit)
I really hope someone will solve my problem. I'm not trying to just let someone else do the work. I validated, checked, debugged, but nothing solved my problem.
My HTML (it's in a modal using Bootstrap):
<div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="signupform" method="post" action="/" role="form">
<div class="modal-body" style="padding-bottom: 5px;">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p class="lead">For creating an account,</p>
<p class="lead text-right">you'll have to give us some information.</p>
<div id="emailgroup" class="form-group">
<label for="signupemail"> Your Emailaddress</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-envelope"></span> </span>
<input type="email" name="signupemail" spellcheck="false" autocomplete="on" required class="form-control" id="signupemail" placeholder="Email">
</div>
<label class="control-label error-label" for="signupemail"></label>
</div>
</div>
<div id="fnamegroup" class="form-group">
<label for="inputfname"> Your Full Name</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-user"></span> </span>
<input type="text" name="fname" required class="form-control" id="inputfname" placeholder="Barack Obama">
</div>
<label class="control-label error-label" for="inputfname"></label>
</div>
</div>
<div id="unamegroup" class="form-group">
<label for="inputuname"> Your Username</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> # </span>
<input type="text" name="uname" required class="form-control" id="inputuname" placeholder="PresidentofAmerica">
</div>
<label class="control-label error-label" for="inputuname"></label>
</div>
</div>
<div id="thepasswordgroup" class="form-group">
<label for="thepassword"> Your Password</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-lock"></span> </span>
<input type="password" name="thepassword" required class="form-control" id="thepassword" placeholder="123456789" autocomplete="off">
</div>
<label class="control-label error-label" for="thepassword"></label>
</div>
</div><br />
<div id="gendergroup">
<label>Your Gender</label>
<div class="radio">
<label class="checkbox-inline"><input type="radio" name="gendergroup" id="gendergroupmale" value="male" checked>I'm a Male</label>
</div>
<div class="radio">
<label class="checkbox-inline"><input type="radio" name="gendergroup" id="gendergroupfemale" value="female">I'm a Female</label>
</div>
</div>
<br />
<div class="form-group">
<label for="taccheckbox"> Terms and Conditions</label>
<div class="col-lg-10">
<div class="input-group"><span class="input-group-addon">
<input id="taccheckbox" name="taccheckbox" type="checkbox" required>
</span>
<input style="cursor:default !important;" type="text" id="something" value="I accept the Terms and Conditions" readonly class="form-control">
</div>
<label class="control-label error-label" for="taccheckbox"></label>
<!-- /input-group -->
</div>
<!-- /.col-lg-6 -->
</div>
</div>
<div class="modal-footer">
<p>
Have already got an account? <strong>Login here!</strong></p>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="signupsubmitbtn" class="btn btn-primary" value="Sign Up">
</div>
</form>
</div>
</div>
</div>
My Javascript/jQuery:
$('#signupform').validate({
rules: {
signupemail: {
required: true,
email: true,
remote: {
url: "/functions/verifysignup.php",
type: "post"
}
},
fname: {
required: true,
minlength: 8,
maxlength: 30
},
uname: {
required: true,
minlength: 6,
maxlength: 20,
remote: {
url: "/functions/verifysignup.php",
type: "post"
}
},
thepassword: {
required: true,
minlength: 5,
maxlength: 20
},
taccheckbox: "required"
},
messages: {
email: {
remote: "This emailaddress is already in use"
},
taccheckbox: {
required: "You have to accept the Terms and Conditions"
},
fname: {
minlength: "At least 8 characters required",
maxlength: "Max. 30 characters"
},
uname: {
minlength: "At least 6 characters required",
maxlength: "Max. 20 characters",
remote: "This username is already in use"
}
},
submitHandler: function (form) {
alert('called');
$('#signupsubmitbtn').prop("disabled", false);
//^[a-zA-Z0-9_-]{6,15}$ username
form.submit();
},
errorPlacement: function (error, element) {
if (element.attr('id') == "taccheckbox") {
error.appendTo(element.parent().parent().next());
} else {
error.appendTo(element.parent().next());
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$('#signupsubmitbtn').prop("disabled", true);
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error').find('label.control-label label').text('');
if ($('.has-error').length === 0) {
$('#signupsubmitbtn').prop("disabled", false);
}
},
success: function (element) {
element.closest('.form-group').removeClass('has-error').addClass('has-success');
if ($('.has-error').length === 0) {
$('#signupsubmitbtn').prop("disabled", false);
}
//element.parent().next().text('');
}
});
My remote PHP script:
<?php
define ('INCLUDE_CHECK',true);
require('connect.php');
if(isset($_REQUEST['signupemail'])){
$email = mysqli_real_escape_string($link, $_REQUEST['signupemail']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE email=\"".$email."\""));
if($thearray[0] > 0){
echo '"This emailaddress is already in use"';
} else {
echo "True";
}
} else if(isset($_REQUEST['uname'])){
$uname = mysqli_real_escape_string($link, $_REQUEST['uname']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE uname=\"".$uname."\""));
$forbiddennames = array(1 => 'super-user','superuser', 'root', 'admin', 'administrator', 'system', 'website', 'site', 'owner', 'manager', 'founder','moderator');
if(in_array(strtolower($_REQUEST['uname']), $forbiddennames)) {
echo '"'.$_REQUEST['uname'].' is a forbidden username"';
} else if($thearray[0] > 0){
echo '"This username is already in use, please choose another"';
} else {
echo "True";
}
}
?>
Everything looks very close to correct to me. One issue is that you have your php script echoing True back, but it has to be true (lower case). That actually matters.
Otherwise, IMO your script looks fine.
The stuff you're saying about it not calling your submitHandler, or only triggering the remote bits doesn't really seem to be the case to me. I copied your code and simply added a bit of debugging (i.e. to console.log when remote gets triggered or when submitHandler gets called) and both got called at the appropriate times.
For instance, if you type a valid email and then click to the next field, it immediately validates the email address.
So whatever issues you're having, are not related to the code you've shown (except for that one error with true vs True).
Here's a working example of your code, for reference: http://jsfiddle.net/ryleyb/tWH9M/1/
In order to test it with remote working teh way you have it setup, you have to find this bit:
signupemail: {
required: true,
email: true,
remote: {
url: '/echo/json/',
data: {
json: function () {
return 'true';
}
},
complete: function (data) {
$('#log').append('remote signupemail triggered<br>');
},
type: 'post'
},
},
And change that return 'true'; to return 'True';

Categories

Resources