jquery-form-validator.js: Form input validates, but form itself fails validation. Only one input in form - jquery-form-validator

I'm using jQuery-Form-Validator and most of it is going fine.
I have a form that contains only an email field and a submit button. The email field validates correctly on blur, but when the form is submitted, I get the error message saying the form isn't valid (not the field).
I'm lost.
Here are all of the code bits...
<form id="form_email" name="form_email" class="justify-content-center" onsubmit="return false;">
<div id="email-group" class="form-group">
<input class="form-control form-control-lg mr-1" type="text" id="email" name="email" placeholder="Email Address" value="" data-validation="email" data-validation-error-msg-container="#email-error-dialog" autocomplete="on" />
<p class="form-control-feedback" id="email-error-dialog"></p>
<p class="text-muted">We will only share your email address with other companies when you explicitly give us permission.</p>
<input type="submit" class="btn btn-primary btn-lg" id="email-next" value="Save" />
</div>
</form>
<script>
$( "#form_email" ).submit(function( event ) {
updateRecord('user_inputs', 'fingerprint', fp2_hash, 'email', $( "email" ).value);
//alert( "Handler for .submit() called." );
//event.preventDefault();
});
$( "#email" ).on( 'validation', function(evt, valid) {
// If it's a valid email address...
if ( valid == true ) {
// Update style
if ( $( "#email-group" ).hasClass( "has-danger" ) ) $( "#email-group" ).removeClass( "has-danger" );
if ( $( "#email" ).hasClass( "form-control-danger" ) ) $( "#email" ).removeClass( "form-control-danger" );
$( "#email-group" ).addClass( "has-success");
$( "#email" ).addClass( "form-control-success" );
} else if ( valid == false) {
// Update style
if ( $( "#email-group" ).hasClass( "has-success" ) ) $( "#email-group" ).removeClass( "has-success" );
if ( $( "#email" ).hasClass( "form-control-success" ) ) $( "#email" ).removeClass( "form-control-success" );
$( "#email-group" ).addClass( "has-danger" );
$( "#email" ).addClass( "form-control-danger" );
$( "#email-error-dialog" ).addClass( "has-danger" );
}
});
</script>
Then the validator script is called and it finishes with:
<script type="text/javascript">
$.validate({
modules : 'html5, toggleDisabled',
forms : '#leads, #form_email',
disabledFormFilter : 'form.toggle-disabled',
showErrorDialogs : false,
successElementClass : 'has-success',
errorElementClass : 'has-danger',
onError : function($form) {
alert('Validation of form '+$form.attr('id')+' failed!');
},
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
return true; // Will stop the submission of the form
},
onValidate : function($form) {
return {
element : $( this),
message : 'This input has an invalid value for some reason'
}
},
onElementValidate : function(valid, $el, $form, errorMess) {
console.log('Input ' +$el.attr('name')+ ' is ' + ( valid ? 'VALID':'NOT VALID') );
},
validateOnBlur : true, // disable validation when input looses focus
errorMessagePosition : 'inline', // Default. Instead of top
scrollToTopOnError : true // Set this property to true on longer forms
});
</script>
You're welcome to look at it live, but you have to take a three-question quiz to get to it. Answers: "I own," "$101-150," and "No Shade."
Thank you for your help!

You probably should remove this part:
onValidate : function($form) {
return {
element : $( this),
message : 'This input has an invalid value for some reason'
}
}
It will always tell the validator that you have an element that is invalid when the form gets submitted.

Related

Protect Post Content and Avoid Page Refresh using AJAX upon Password Submit

This is for WordPress, just to make that clear. I'm asking here since I suspect that I need to provide a bounty on this question (worth 400).
I need to add AJAX to my form submit to avoid page reload / page refresh. I have tried several different versions and none of them are working.
The general idea here is to protect parts of a post whereof that part is code wrapped in <pre> and <code> tags.
These tags are from the prismjs highlighter and looks like this:
<pre><code class="language-php">code here</code></pre>
These tags have four different classes;
PHP
HTML
CSS
JS
This is why the preg_replace uses the ('/(<pre[^>]*>\s*<code[^>]*>) formatting as it needs to cover (handle) the class added.
Furthermore, a cookie is set so that once the user has provided a correct password, the password is remembered. The user should not have to re-enter the password each time they view a post with protected content.
I have an empty DIV acting as a placeholder for showing messages (success and error). The idea here is to show an error if the user submits an incorrect password. If the password match, show the content (code).
This is the code I am working on:
add_filter( 'the_content', 'wrap_code_in_shortcode' , 9 );
function wrap_code_in_shortcode( $content ) {
if ( ! in_category( 'premium' ) ) return $content;
$content = preg_replace('/(<pre[^>]*>\s*<code[^>]*>)/',"[protected]$1", $content);
$content = preg_replace('/(<\/code>\s*<\/pre>)/', "$1[/protected]", $content);
return $content;
}
add_shortcode( 'protected', 'protected_function' );
function protected_function($atts, $content=null){
$userpass = isset( $_REQUEST['password']) ? $_REQUEST['password'] : (isset($_COOKIE['userpass']) ? $_COOKIE['userpass'] : NULL );
if ( in_array( $userpass, array('testpw') ) ) {
$return_code = do_shortcode( $content );
} else {
$return_code = '<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
<div id="errorPWdata"></div>
<form method="post" onsubmit="protectedFunction(this);">
<input required style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;" type="text" placeholder=" Password Here" name="password" id="userpass">
<input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;" id="protectedButton" type="submit" value="Submit">
</form>';
?>
<script>
function protectedFunction(form) {
$('#protectedButton').on( 'click', function(e) {
e.preventDefault();
$.ajax({
success: function(data) {
$("#errorPWdata").html(data);
},
error: function() {
alert("Password record error. Contact the administrator.");
}
});
document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
}
}
</script>
<?php
}
return $return_code;
}
I learned to details your code snippet and notice mistakes.
Please, read everything firstly, then you could try.
Mistake 1
Shortcode has been defined with a wrong function name
add_shortcode( 'protected', 'shortcode_protected' );
Should be replaced with
add_shortcode( 'protected', 'bio_protected_function' );
Mistake 2
Script tag should be replaced by the enqueueing system to guarantee script sequences.
The snippet
<script>
function protectedFunction(form) {
$('#protectedButton').on('click', function (e) {
e.preventDefault();
$.ajax({
success: function (data) {
$("#errorPWdata").html(data);
},
error: function () {
alert("Password record error. Contact the administrator.");
}
});
document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
}
}
</script>
Should be replaced with this one
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script(
'bio-shortcode-protected',
get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
[ 'jquery' ],
'1',
true
);
} );
wp_enqueue_scripts();
An appropriate bio-shortcode-protected.js file should be created
path-to-your-theme/assets/js/bio-shortcode-protected.js (Content of the file in next mistake)
Mistake 3
By default WordPress loads jQuery as a global JavaScript object
jQuery should works meanwhile $ probably won't. The script should start with jQuery wrapper to guarantee $ alias working.
Provided Script has incorrect syntax. There should be a close
parentese symbol )
Better to use submit handler instead of click handler. I simplified your handler by handling submit instead of click. Clicking input button triggers submit and click handler not required.
Finally, the bio-shortcode-protected.js content should be
jQuery(function($){
const settings = window.bioShortcodeData;
function init() {
$('#protectedForm').on( 'submit', function(e) {
e.preventDefault();
const form = this;
$.post({
url: settings['endpoint'],
data: {
'action': settings['action'],
'bio-post-id': settings['post-id'],
'nonce': settings['nonce'],
'password': form.userpass.value,
},
success: function(data) {
if (!data.status) {
alert(data.message);
$('#errorPWdata')
.empty()
.append(data.message);
return;
}
if (data.isValidPassword) {
document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
}
$('#bio-protected-content').replaceWith(data.content);
init() // for reattach submission handler
},
error: function() {
alert("Server error");
}
});
})
}
init();
})
And appropriate little bit improved shortcode template should look like:
function bio_protected_function( $atts, $content = null ) {
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script(
'bio-shortcode-protected',
get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
[ 'jquery' ],
'1',
true
);
wp_localize_script(
'bio-shortcode-protected',
'bioShortcodeData',
[
'post-id' => get_the_ID(),
'nonce' => wp_create_nonce( 'bio-shortcode' ),
'endpoint' => admin_url( 'admin-ajax.php' ),
'action' => 'bio_protected_code'
]
);
} );
wp_enqueue_scripts();
if ( bio_validate_the_password() ) {
return do_shortcode( $content );
}
ob_start();
?>
<div class="bio-protected-content" id="bio-protected-content">
<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
<div id="errorPWdata"></div>
<form method="post" id="protectedForm">
<input required
style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;"
type="text" placeholder=" Password Here" name="password" id="userpass">
<input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;"
id="protectedButton" type="submit" value="Submit">
</form>
</div>
<?php
return ob_get_clean();
}
Mistake 4
If the form will be submitted what would heppend - is WordPress starts to build content of the page, firstly header, the content (the_content filter), then footer. And checking password inside shortcode not so good idea. This way sending unnecessary page chunks. The only thing need to fetch by AJAX is clean apropriate post content.
This is where ajax-endpoint comes into play. Endpoint should be created by placing the snippet to functions.php file:
add_action( 'wp_ajax_nopriv_bio_protected_code', 'bio_protected_code_endpoint' );
add_action( 'wp_ajax_bio_protected_code', 'bio_protected_code_endpoint' );
function bio_protected_code_endpoint() {
$is_valid_nonce = wp_verify_nonce( $_REQUEST['nonce'], 'bio-shortcode' );
if ( ! $is_valid_nonce ) {
wp_send_json(
[
'status' => false,
'message' => 'Invalid nonce',
]
);
exit;
}
$post_id = $_REQUEST['bio-post-id'];
$post_type = get_post_type( $post_id );
$available_post_type = 'your-post-type';
if ( $available_post_type !== $post_type ) {
wp_send_json(
[
'status' => false,
'message' => 'Not available post type',
]
);
exit;
}
global $post;
$post = get_post( $post_id );
$content = apply_filters( 'the_content', $post->post_content );
wp_send_json(
[
'status' => true,
'isValidPassword' => bio_validate_the_password(),
'content' => $content
]
);
exit;
}
And password validation function
function bio_validate_the_password() {
$userpass = $_REQUEST['password'] ?? $_COOKIE['userpass'] ?? null;
return in_array( $userpass, [ 'testpw' ] );
}
Last words:
I don't recommend set password in Cookie. It's potential security breach.
Better to set Session password variable. But this way not much better.
There is a good answer why not to store password in Session and what to do instead.
Is it secure to store a password in a session?
Please try with below code.
Shortcode handling part:
// add [protected] shortcode to content.
add_filter( 'the_content', 'wrap_code_in_shortcode' , 9 );
function wrap_code_in_shortcode( $content ) {
if ( ! in_category( 'premium' ) ) return $content;
$content = preg_replace('/(<pre[^>]*>\s*<code[^>]*>)/',"[protected]$1", $content);
$content = preg_replace('/(<\/code>\s*<\/pre>)/', "$1[/protected]", $content);
return $content;
}
// function to check if password is valid
function is_user_password_valid($userpass, $post_id) {
return in_array( $userpass, array('test') );
}
// define shortcode. you can combine(merge) this section with wrap_code_in_shortcode()
add_shortcode( 'protected', 'shortcode_protected' );
function shortcode_protected($atts, $content=null){
$userpass = isset( $_REQUEST['password']) ? $_REQUEST['password'] : (isset($_COOKIE['userpass']) ? $_COOKIE['userpass'] : NULL );
$post_id = get_the_ID();
if ( is_user_password_valid($userpass, $post_id) ) {
$return_code = do_shortcode( $content );
} else {
$return_code =
'<div id="protected-area">
<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
<form method="post" onsubmit="getProtectedContent(event);">
<input required type="text" placeholder=" Password Here" name="password">
<input type="submit" value="Submit">
</form>
</div><!-- end of #protected-area -->';
$return_code .= '<script>
function getProtectedContent(event) {
event.preventDefault();
let password = event.target.elements.password.value;
jQuery.ajax({
url: "' . admin_url('admin-ajax.php') . '" ,
method: "POST",
data: {
action: "get_protected_content",
post_id: ' . $post_id . ',
password
},
success: function(result) {
if (result.success) {
jQuery("#protected-area").html(result.data);
document.cookie = "userpass=" + password + "; path=/";
} else {
alert(result.data);
}
},
error: function() {
alert("Something is wrong.");
}
});
return false;
}
</script>';
}
return $return_code;
}
Ajax Request Handling Part:
add_action( 'wp_ajax_get_protected_content', 'get_protected_content' );
add_action( 'wp_ajax_nopriv_get_protected_content', 'get_protected_content' );
function get_protected_content() {
// validation
if ( empty( $_POST['post_id'] ) ) {
wp_send_json_error( 'Wrong Post ID' );
}
$post_id = (int)$_POST['post_id'];
if ( empty( $_POST['password'] ) || ! is_user_password_valid( $_POST['password'], $post_id ) ) {
wp_send_json_error( 'Wrong Password' );
}
$content = get_post_field( 'post_content', $post_id );
// var_dump($content);
if ( preg_match( '/(<pre[^>]*>\s*<code[^>]*>.*<\/code>\s*<\/pre>)/', $content, $matches ) ) {
wp_send_json_success( apply_filters( 'the_content', $matches[1] ) );
} else {
wp_send_json_error( 'No Protected Content Found' );
}
}
Hope this code help you.

How to get jQuery autocomplete value through select dropdown id

I am going to develop three autocomplete dropdown boxes using jQuery ajax for country state and city on my laravel project. I can implement simple html dropdowns using ajax. But while using jQuery autocomplete it automatically adds an input field in which it puts the value over selecting options from dropdown.
The issue is I am getting only values as text string from input field where I need the id of country which is my database. Previously I was able to get this id using html select element by using the value attribute but it seems there no way to get this id from input field.
How to get this and moreover how to use auto complete for multiple select boxes which needs to be auto changed by selecting options from any select boxes?
html select elements
<div class="ui-widget">
<p style="float:right;display:block;font-size:15px;">
<select id="country" name="sel_countries" required=""><option value="">Select Country</option>
#foreach ($countries as $country)
<option value="{{ $country->id }}">
{{ $country->name }}
</option>
#endforeach
</select>
<select id="state" name="sel_states" required=""><option value="">Select State</option></select>
<select id="city" name="sel_cities" required=""><option value="">Select City</option></select>
</p></div>
html ajax request
$('#country').change(function(){
var cid = $(this).val();
if(cid){
$.ajax({
type:"get",
url:"<?php echo $url; ?>/getStates/"+cid,
success:function(res)
{
if(res)
{
$("#state").empty();
$("#city").empty();
$("#state").append('<option>Select State</option>');
$.each(res,function(key,value){
$("#state").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
$('#state').change(function(){
var sid = $(this).val();
if(sid){
$.ajax({
type:"get",
url:"<?php echo $url; ?>/getCities/"+sid,
success:function(res)
{
if(res)
{
$("#city").empty();
$("#city").append('<option>Select City</option>');
$.each(res,function(key,value){
$("#city").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
bootstrap autocomplete code
$( function() {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
classes: {
"ui-tooltip": "ui-state-highlight"
}
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.attr( "height", "" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: "false"
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.on( "mousedown", function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.on( "click", function() {
input.trigger( "focus" );
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
$( "#country" ).combobox();
$( "#toggle" ).on( "click", function() {
$( "#country" ).toggle();
});
} );
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding-top: 2px;
padding-bottom: 5px;
padding-right: 5px;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<p style="float:right;display:block;font-size:15px;">
<select id="country" name="sel_countries" required=""><option value="">Select Country</option>
<option value="1">
INDIA
</option>
<option value="1">
USA
</option>
<option value="1">
UK
</option>
<option value="1">
AUSTRALIA
</option>
<option value="1">
BRAZIL
</option>
</select>
<select id="state" name="sel_states" required=""><option value="">Select State</option></select>
<select id="city" name="sel_cities" required=""><option value="">Select City</option></select>
</p></div></div>

Using jquery validation 1.17.0 with Bootstrap 4.0.0 beta

I'm working on a project and noticed that bootstrap 4.0.0 beta does not use glyphicons anymore, so how could I achieve the same effect as the 2nd example "Using feedback icons" shown in the link here JQuery-validation and Bootstrap using font-awesome 4.7.0? I've included the output of the validation below for better clarity:
Currently this is what I've got:
HTML
<div class="form-group">
<label class="col-sm-4 control-label df-label" for="first_name">* First name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label df-label" for="last_name">* Last name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" />
</div>
</div>
....
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-outline-success my-2 my-sm-0" id="send" name="send" value="Send">Send</button>
</div>
</div>
CSS
.has-danger .control-label,
.has-danger .help-block,
.has-danger .form-control-feedback {
color: #d9534f;
}
jQuery
$( "#contact-form" ).validate({
rules: {
first_name: "required"
,last_name: "required"
,email: {
required: true
,email: true
}
,message: {
required: true
,minlength: 10
}
}
,messages: {
first_name: "Please enter your First name"
,last_name: "Please enter your Last name"
,email: "Please enter a valid Email address"
,message: {
required: "Please enter a Message"
,minlength: "Your message must consist of at least 10 characters"
}
}
,meta: "validate"
,errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
// Add `has-feedback` class to the parent div.form-group
// in order to add icons to inputs
element.parents( ".col-sm-5" ).addClass( "has-feedback" );
element.parents( ".col-sm-8" ).addClass( "has-feedback" );
if ( element.prop( "type" ) === "checkbox" ) {
error.insertAfter( element.parent( "label" ) );
} else {
error.insertAfter( element );
}
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !element.next( "span" )[ 0 ] ) {
$( "<span class='fa fa-times form-control-feedback'></span>" ).insertAfter( element );
}
},
success: function ( label, element ) {
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !$( element ).next( "span" )[ 0 ] ) {
$( "<span class='fa fa-check form-control-feedback'></span>" ).insertAfter( $( element ) );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-danger" ).removeClass( "has-success" );
$( element ).parents( ".col-sm-8" ).addClass( "has-danger" ).removeClass( "has-success" );
$( element ).next( "span" ).addClass( "fa-times" ).removeClass( "fa-check" );
},
unhighlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-danger" );
$( element ).parents( ".col-sm-8" ).addClass( "has-success" ).removeClass( "has-danger" );
$( element ).next( "span" ).addClass( "fa-check" ).removeClass( "fa-times" );
}
});
And here is my output so far:
I'm guessing your issue is first the placement of the feedback icon and second the color of the elements? There were some big changes between the alpha and beta versions of bootstrap (and also bootstrap 3), esp. in regards to form validation.
First, to place the icons correctly you'll need to add styling which equates to what was in bootstrap 3 and no longer in bootstrap 4 beta...here's what I'm using
.fa.valid-feedback,
.fa.invalid-feedback {
position: absolute;
right: 25px;
margin-top: -50px;
z-index: 2;
display: block;
pointer-events: none;
}
.fa.valid-feedback {
margin-top: -28px;
}
The classes have changed as the beta uses the 'state' of the control which your posted code doesn't reflect, so your above code may not work. Anyway, you'll need to add 'was-validated' class to the form either in the success or highlight/unhighlight callbacks
$(element).closest('form').addClass('was-validated');
I would also recommend using the new element and classes for form control help text
errorElement: 'small',
errorClass: 'form-text invalid-feedback',
I assume you don't want to purchase Glyphicons, so you could make the switch to Font Awesome. View the source of the example that you provided and see how "glyphicon-ok" and "glyphicon-remove" are being used. The equivalent "fa-check" and "fa-times" icons look like the closest matches.
Related issues:
Glyphicons no longer supported in Bootstrap 4
how to use Glyphicons in bootstrap 4 and angular2?

Wordpress ajax form nonce fails

I have a email form in Wordpress and I'm using ajax to with it.
I'm creating a nonce in the form and checking it before I send the email.
The nonce fails but the output shows it is the same nonce.
Simified code:
The email form
<form class="email-form" role="form">
<div class="form-group">
<label>Full Name</label>
<input type="text" class="email-name input-lg"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="email-email input-lg"/>
</div>
<input type="hidden" name="ajax-nonce" id="ajax-nonce" value="' <?php echo wp_create_nonce( 'email-nonce' ); ?>'" />
<div class="form-group email-submit">
<button class="btn-green email-submit">Send</button>
</div>
</form>
The js
$('.email-submit').on('click', function(e){
e.preventDefault();
var mc_name = $('.email-name').val();
var mc_email = $('.email-email').val();
var mc_nonce = $('#ajax-nonce').val();
alert(mc_nonce);
classData = {
'type' : 'post',
'action' : 'classajax-submit',
'dataType' : 'jsonp',
'crossDomain' : true,
'nonce' : mc_nonce,
'the_name' : mc_name,
'the_email' : mc_email,
}
$.post(TheAjax.ajaxurl, classData).done(function(result){
if(result == 'success') {
//success message
}
}, 'jsonp');
})
Functions.php
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script('scripts',get_template_directory_uri() . '/js/compiled/main.min.js', array('jquery'));
//
wp_localize_script( 'scripts', 'TheAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_ajax_nopriv_classajax-submit', 'classajax_submit' );
add_action( 'wp_ajax_classajax-submit', 'classajax_submit' );
function classajax_submit() {
$nonce = stripslashes($_POST['nonce']);
echo 'nonce in php ' . $nonce;
if ( ! wp_verify_nonce( $nonce, 'email-nonce' ) ) {
die ('Email Busted!');
}else{
}
}
First of all you need not to create hidden fields use this it will create it automatically
<?php wp_nonce_field( 'your_action', 'put_name' ); ?>
while checking if(wp_verify_nonce( $_POST[ 'put_name' ], 'your_action' ))
try this
You could use check_ajax_referrer, there's an example in the documentation: https://codex.wordpress.org/Function_Reference/check_ajax_referer

special datepicker for date range

I need urgently to make a range datepicker for two dates :start date and end date.
Start date cannot be before date time now and end date cannot be before choosed start date.
Here is an example of what i want.Can somebody tell me what to use to make this?
http://rezervari.hotelalpin.ro/
this is what i tried but is not working:
</head>
#using (Html.BeginForm("SearchFree", "Reservation", FormMethod.Get,new {id = "form" }))
{
<h7>Introduceti perioada Rezervarii</h7>
<div class="editor-label">
<label id="cautare" for="StartDate">Data Intrare: </label>#(Html.JQueryUI().Datepicker("StartDate").DateFormat("mm-dd-yy").MinDate(DateTime.Today).ShowButtonPanel(true).ChangeYear(true).ChangeMonth(true).NumberOfMonths(2))
</div>
<div class="editor-label">
<label id="cautare" for="EndDate">Data Iesire: </label>#(Html.JQueryUI().Datepicker("EndDate").DateFormat("mm-dd-yy").MinDate(DateTime.Today).ShowButtonPanel(true).ChangeYear(true).ChangeMonth(true).NumberOfMonths(2))
</div>
<p>
<input id="buton1" type="submit" value="Cauta camere libere" />
</p>
}
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod("EndDate", function (value, element) {
var startDate = $('.StartDate').val();
return Date.parse(startDate) <= Date.parse(value);
}
, "* End date must be after start date");
$('.form').validate();
});
</script>
The jquery UI datepicker has a date range option that you can use. You can set it up like this:
HTML:
<label for="from">From</label>
<input type="text" id="from" name="from"/>
<label for="to">to</label>
<input type="text" id="to" name="to"/>
Javascript:
$(function() {
$("#from").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onSelect: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$("#to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onSelect: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
Should be able to do that with a JQuery date picker!
You can then use some Javascript/JQuery validation to alert the user if they enter a date outside the range you specify.
You can restrict the range of selectable dates using the minDate and maxDate options of jQuery datepicker. See an example here:
http://jqueryui.com/demos/datepicker/#min-max
<input type="text" id="tbStartDate" value="" disabled="disabled" />
<input type="text" id="tbEndDate" value="" disabled="disabled" />
<script type="text/javascript">
$(document).ready(function () {
$("#tbStartDate").datepicker({
//minDate: new Date(2007, 1 - 1, 1), //use for Date time now
dateFormat: 'dd-mm-yy',
showOn: 'button',
buttonImageOnly: true,
buttonImage: '/Content/Calendar.png',
buttonText: 'Click here (date)',
onSelect: function (dateText, inst) {
var $endDate = $('#tbStartDate').datepicker('getDate');
$endDate.setDate($endDate.getDate() + 1);
$('#tbEndDate').datepicker('setDate', $endDate).datepicker("option", 'minDate', $endDate);
},
onClose: function (dateText, inst) {
//$("#StartDate").val($("#tbStartDate").val());
}
});
$("#tbEndDate").datepicker({
//minDate: new Date($("#tbStartDate").datepicker('getDate')),
dateFormat: 'dd-mm-yy',
showOn: 'button',
buttonImageOnly: true,
buttonImage: '/Content/Calendar.png',
buttonText: 'Click here (date)',
onSelect: function (dateText, inst) {
$('#tbStartDate').datepicker("option", 'minDate', new Date($("#tbEndDate").datepicker('getDate')));
},
onClose: function (dateText, inst) {
//$("#EndDate").val($("#tbEndDate").val());
}
});
var $endDate = $('#tbStartDate').datepicker('getDate');
$endDate.setDate($endDate.getDate() + 1);
$('#tbEndDate').datepicker('setDate', $endDate).datepicker("option", 'minDate', $endDate); });
</script>

Resources