Simple jquery validation - custom position error message placement - javascript

I am using jquery validate plugin to validate number in a form , how can i place the returned error message under the input button , i am unable to achieve,
Here is my image with the issue and what i need,pls check - http://i.imgur.com/Gt5aNxs.png
Please suggest me how to put the error message in a custom Div under the button instead of default underneath.
Here is my code:
<section id="contact" class="content">
<div class="container">
<h2>Contact Form Demo</h2>
<div class="row">
<div class="span12 contact-form">
<form action="mail.php" method="POST" class="form-horizontal contact-form" id="contact-form">
<!--<?php $formKey->outputKey(); ?> -->
<fieldset>
<div class="control-group">
<label class="control-label" for="inputPhone">Phone</label>
<div class="controls">
<input class="input-80" name="phone" type="text" id="inputPhone" placeholder="inc. country & area code">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value="Send" class="btn" id="btn-place">Send!</button>
</div>
<div >place here</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</section>
<!-- javascript -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script>
// contact form validation
$(document).ready(function(){
$('#contact-form').validate(
{
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
minlength: 11,
required: false,
number: true
},
subject: {
minlength: 3,
required: true
},
message: {
minlength: 20,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
}
});
// contact form submission, clear fields, return message,script no shown here
</script>

All you need to do is specify the errorLabelContainer in your options and specify the div you want the errors to go into:
$('#contact-form').validate({
//all your other options here
errorLabelContainer: '#errors'
});
Then just make sure you specify that your place here div has the id errors like this:
<div id="errors"></div>
See a working example here: http://jsfiddle.net/ryleyb/aaEFQ/ (note that I also specified the wrapper option, which you'll probably want if there are multiple errors).

errorPlacement: function(error, element) {
if((element.attr('name') === 'color[]')){
error.appendTo("div#errors");
}
else if(element.attr('name') === 'font[]' ){
error.appendTo("#font-error");
}
else{
element.before(error);
}
}

Related

Password change jQuery validation error message does not appear

I face a problem when I enter wrong matching password - the jQuery validation error message not appear.
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#passwordchange').validate({
rules:{
newpass:{
required: true
},
retypepass:{
required:true,
equalto: '#newpassword'
}
},
messages:{
retypepass:{
equalto:"should enter matching pass"
}
}
});
Here is the full code on codepen
AS #Azametzin's comment and the document, You should use equalTo instead of equalto
Syntax
equalTo( other ) Returns: Boolean
Description: Requires the element
to be the same as another one
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#passwordchange').validate({
rules:{
newpass:{
required: true
},
retypepass:{
required:true,
equalTo: '#newpassword'
}
},
messages:{
retypepass:{
equalTo:"should enter matching pass"
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.1/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<form method="GET" action="" id="passwordchange">
<div class="form-row">
<div class="form-group row no-gutters col-12">
<label for="newpassword" class="col-md-3">كلمة المرور الجديدة</label>
<div class="col-md-9">
<input type="password" class="form-control" id="newpassword" name="newpass" placeholder="GHIBKL#$*132581">
</div>
</div>
</div>
<div class="form-row">
<div class="form-group row no-gutters col-12">
<label for="retype" class="col-md-3">إعادة كلمة المرور</label>
<div class="col-md-9">
<input type="password" class="form-control" id="retype" name="retypepass" placeholder="GHIBKL#$*132581">
</div>
</div>
</div>
<button type="submit">submit</button>
</form>

jQuery form validate plugin activate

I have three forms on my website: register-form, login-form and article-form.
All three forms are validated via the plugin, all inside the one javascript file.
The register-form and login-form's work as expected and actually validate the form, yet the article-form one does not? the same code is used throughout and there are no errors that I can see...
Do the stylesheets need to be ordered in a certain way?
Is there a limit to the number of forms in a certain form validate file?
Article Form - Inside the .js file
//validate insertArticles form
//validate
$(function(){
$('#article-form').validate(
{
rules:{
heading: {
required: true,
maxlength:75,
},
topic: {
required: true,
maxlength: 15,
},
summary: {
maxlength: 100,
},
text: {
required: true
}
}
}); //valdate end
}); //function end
HTML article-form
$(function(){
$('#article-form').validate(
{
rules:{
heading: {
required: true,
maxlength:75,
},
topic: {
required: true,
maxlength: 15,
},
summary: {
maxlength: 100,
},
text: {
required: true
}
}
}); //valdate end
}); //function end
<!--Incude Head-->
<?php require_once '../view/header.php';?>
<body>
<div id="wrapper"><!--wrapper start-->
<!--Include Navbar-->
<?php require_once '../view/navbar.php';?>
<div class="container" id="content"><!--container start-->
<div class="jumbotron"><!--jumbotron start-->
<!--Form 1-->
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" id="Question">
<form class="article" id="article-form" method="post" enctype="multipart/form-data">
<ol>
<li>
<label for="heading">Heading</label> <span id="headingMessage"></span>
<input name="heading" id="heading" class="form-control" type="text">
</li>
<li>
<label for="topic">Topic</label> <span id="topicMessage"></span>
<input name="topic" id="topic" class="form-control" type="text" list="football" >
<datalist id="football">
<option value="Scotland"></option>
<option value="England"></option>
<option value="Spain"></option>
</datalist>
</li>
<li>
<label for="summary">Summary</label>
<input name="summary" id="summary" class="form-control">
</li>
<li>
<label for="thumbnail">Thumbnail</label> <span id="thumbnailMessage"></span>
<!-- <input name="thumbnail" id="thumbnail" class="form-control" type="text" required> -->
<input type="file" name="file" id="file">
</li>
<li>
<label for="articleText">Text</label>
</div>
<textarea name="articleText" id="articleText" class="md-textarea form-control"></textarea>
</li>
<li>
<div class="g-recaptcha" data-sitekey="xx-0xitZ7ZeZ"></div>
</li>
</ol>
<input class="btn btn-success" id="formButton" type="submit" name="submit"value="Submit" name="submit">
<input class="btn btn-danger" id="formButton" type="reset" value="Reset">
</form>
<script>
//$("#articleText").jqte();
</script>
<?php require '../controller/NewArticle.php';?>
</div>
</div><!--jumbotron end-->
</div><!--container end-->
<!-- Include Footer -->
<?php require_once '../view/footer.php';?>
</div><!--wrapper end-->
</body>
<script src ="../controller/FormValidate.js"></script>
<script src="../js/bootstrap.min.js"></script>
<!-- jQuery Validate Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.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://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script><!--Google API - Captcha -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</html>
</body>
<script src ="../controller/FormValidate.js"></script>
<script src="../js/bootstrap.min.js"></script>
<!-- jQuery Validate Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.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://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script><!--Google API - Captcha -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="../controller/FormHelp.js"></script>
<!-- Text editor plugin -->
</html>
For an example, I will include the code from my register form
//validate
$(function(){
$.validator.addMethod('strongPassword', function(value, element) {
return this.optional(element)
|| value.length >= 8
&& /\d/.test(value)
&& /[a-z]/i.test(value)
&& /[A-Z]/i.test(value)
&& /[!\#\#\$\%\^\&\*\(\)\_\+\.\,\;\:]/i.test(value);
}, 'Password not strong enough - include: special character, letters and number')
$('#register-form').validate({
rules:{
email: {
required: true,
email: true
},
password:{
required: true,
strongPassword: true
},
confirmPassword:{
required: true,
equalTo: '#password'
},
firstname: {
required: true,
nowhitespace: true,
lettersonly: true
},
lastname: {
required: true,
nowhitespace: true,
lettersonly: true
},
mobileNumber: {
required: true,
digits: true,
phonesUK: true
},
username:{
required:true
}
},
messages: {
email: {
required: 'Please enter an email address',
email: 'Please enter a <i>valid</i> email address,'
},
mobileNumber:{
required: 'Please enter a mobile number <b>(digits only)</b>',
mobileNumber: "Please enter a <i>valid</i> UK mobile number"
}
}
}); //valdate end
}); //function end

how to add multi captcha in same page and check both checkbox its fill

I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.

Jquery validator addmethod minor issue

im new to jquery validator, im trying to use regex to check if numbers, capital and special characters are included. I have the following html
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row white-bg spacepad">
<div id="keypass">
<form method="POST" class="form-horizontal" id="keyform" name="keypasser">
<div class="form-group"><label class="col-sm-2 control-label">Decryption Key For EPins</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypassx" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Confirm Decryption Key</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypass2" /></div>
</div>
<input type="submit" class="btn btn-primary btn-rounded btn-block" value="Submit" />
</form>
</div>
</div>
and the following jquery, when i remove the addmethod it works, please what am i doing wrong
<script type="text/javascript">
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='keypasser']").validate({
// Specify validation rules
rules: {
keypassx: {
required: true,
minlength: 8,
passchecker: true,
},
keypass2: {
required: true,
equalTo: "#keypassx",
}
},
// Specify validation error messages
messages: {
keypassx: {
required: "Epins password required",
minlength: "Minimum length allowed is 8 characters",
passchecker: "Password should contain numbers, special characters and one uppercase",
},
keypass2: {
required: "Confirmation password requied",
equalTo: "Password does not match Epins Password",
}
},
$.validator.addMethod("passchecker",
function(value, element) {
return /^[A-Za-z0-9\d=!\-#._*]*$/.test(value);
});
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
</script>
kindly help out
Please try to use regular expression as
var patt = new RegExp("e");
var res = patt.test(str);
You directly use the regular expression. Please create object and try it.
The addMethod function accepts three params check the docs:
$.validator.addMethod("passchecker",
function(value, element) {
if(/^[A-Za-z0-9\d=!\-#._*]*$/.test(value)) {
return true;
} else {
return false;
}
}, "Your validation message goes here");

how to validate a form for checkbox

I am trying to validate my checkboxes to ensure that a user clicks at least one checkbox. I am getting checkbox Names from the database. Can anyone solve this please.
$(function(){
$("#userFrm").validate({
rules: {
Item1: {
required: true,
},
},
messages: {
Item1: "Check atleast one box",
}
});
}
<form class="form-horizontal" action="" method="post" name="groupFrm" id="groupFrm">
<div class="control-group">
<label class="control-label">
Access Permission
<span class="error">*</span>
</label>
<div class="controls">
<div class="text-group">
{section name=source loop=$source}
<input type="checkbox" name="option1[]" id="Item1" class="first" {if in_array($source[source].id,$permission_user,true)} checked="checked"{/if} value="{$source[source].id}" />
{$source[source].mod_name}
{/section}
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" name="edit_permission" id="edit_permission" value="Update" class="btn btn-success " onclick="validate()">
</div>
</form>
You have use custom validation code to validate check box.
Try this.
$.validator.addMethod('yourRuleName', function (val, elm, param) {
//Validation code Here
return valid;
}, 'Your error message here');
$('#userFrm').validate({
rules: {
item1: {
yourRuleName: true
}
}
});
This will return true if at least one was checked:
$("input[type=checkbox]:checked").length>0
Or, this will count only the checked checkboxes within that form of yours:
$("#groupFrm:checkbox:checked").length>0

Categories

Resources