I would like to use the ParsleyJS Form Validation Library to validate a form that I'm constructing within a SweetAlert2 modal.
Here's my code:
HTML
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#11.1.5/dist/sweetalert2.all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.2/parsley.min.js"></script>
Check Zip Code
JS
$(function() {
const $btnCheckZip = $('.btn-checkzip');
$btnCheckZip.on('click', function() {
Swal.fire({
title: 'Check Product X Availability',
html: '<p>Enter your zip code below to see if product X is currently available in your area.</p><div class="error-msg"></div><div id="form-msg"></div><form id="form-checkzip" class="form"><input type="text" name="lookup" id="lookup" class="swal2-popup-input" placeholder="Enter Zip Code" value="" data-parsley-class-handler="error-msg" data-parsley-validation-threshold="5" data-parsley-pattern="^[0-9]{5}(?:-[0-9]{4})?$" data-parsley-pattern-message="Please enter a valid zip code." data-parsley-required /></form>',
showCloseButton: true,
confirmButtonText: 'Check Now',
showLoaderOnConfirm: true,
preConfirm: () => {
const inputLookup = Swal.getPopup().querySelector('#lookup').value;
const $formLookup = Swal.getPopup().querySelector('#form-checkzip');
//Trying to Bind/Trigger Parsley Validation Event
$formLookup.parsley().validate();
return {
lookup: inputLookup
}
}
});
});
});
Notes
I have tried binding Parsley to the form with both the "data-parsley-validate" and form.parsley(); approaches. Neither have worked for me.
My assumption is that it will need to be bound once the form is available in the DOM. So, I've tried the didOpen and didRender hooks in addition to preConfirm. No luck.
Question
So, my question is, simply, how can I get Parsley to bind to the form that's constructed by SweetAlert2 so that clicking the "Check Now" button will trigger validation?
Related
Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example
Sorry for keep asking this, but I just can't figure it out. I've reduced the question to just the bare minimum.
How can I validate a dynamically generated form? Below is my attempt, but as seen, it shows up as passing validation.
https://jsfiddle.net/j2pgobze/1/
<form id="myForm">
<input type="text" name="email" id="email" value="bademail" >
</form>
<button id="validate">validate</button>
var myValidateObj = {
rules: {
email: {
email: true
}
}
};
$(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#validate').click(function () {
//Validate the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
console.log('Option 1', $('#myForm'), $('#email'), $('#email').val(), validate1.element('#email'), $('#email').valid(), $('#myForm').valid());
//Validate dynamically created form
var input = $('<input />', {
type: 'text',
name: 'email',
value: 'bademail'
});
//input.prop('value', 'bademail');
var form = $('<form />').append(input);
var validate = form.validate(myValidateObj);
console.log('Option 2', form, input, $('#email').val(), validate.element(input), input.valid(), form.valid());
});
});
The button needs to be inside the form and be a type="submit" in order for the plugin to capture the click.
Do not put .validate() within a click handler (See item 1). It's only used to initialize the plugin on a form. Exception, below we are creating the new form within a click handler and then immediately calling .validate() on the new form.
With these two small changes, the validation on the static form is working: jsfiddle.net/j2pgobze/3/
I rewrote your DOM manipulation code for clarity. I simply duplicated the HTML for the form and gave it a new ID: http://jsfiddle.net/zem84tfp/
$(function () {
// INITIALIZE plugin on the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
$('#newform').one('click', function () {
// code here to create new form; give it new ID
// do not duplicate ID on anything else
// INITIALIZE plugin on the new form
var validate = $('#myForm2').validate(myValidateObj);
});
});
I want to display one error message at the top, if validation fails. I don't want to use errorPlacement option. Instead I want to show the message in the Bootstrap alert.
Here is my HTML:
<form method="POST" action="/role" accept-charset="UTF-8" id="roles_form">
<div class="alert alert-danger vd_hidden">
<span class="vd_alert-icon"><i class="fa fa-exclamation-circle vd_red"></i></span>
Please select a role.
</div>
<input id="role_administrator" name="role" type="radio" value="administrator">
<label for="role_administrator">Administrator</label>
<input id="role_manager" name="role" type="radio" value="manager">
<label for="role_manager">Manager</label>
<input type="submit" value="Submit">
</form>
Here is my JavScript:
var roles_form = $('#roles_form');
var error_roles_form = $('.alert-danger', roles_form);
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
debug: true,
rules: {
role: "required"
},
invalidHandler: function (event, validator) { //display error alert on form submit
error_roles_form.fadeIn(500);
},
});
This does not work. Neither it does any validation (form gets submitted, if I remove the debug option) nor does it show any error.
Update:
After looking at the solution provided by Sparky, I realised that I am using a plugin to hide radio elements and replace with a style-able object. As the radio elements were hidden, jQuery Validation failed to validate them properly with my JavaScript code. What surprised me is that it did not show any JavaScript error, even with debug mode on.
Quote OP:
"This does not work. Neither does any validation (form gets submitted, if I remove the debug option) nor [does] it shows any error."
Actually, the code you posted is working: http://jsfiddle.net/TTJB7/
Quote OP:
"I want to display one error message at the top, if validation fails. I don't want to use errorPlacement option."
For placing the error message into a box, you'll need the errorLabelContainer option. So instead of the default behavior of putting error messages next to each input (errorPlacement), the errorLabelContainer will put the messages into one specified container that is hidden/shown automatically.
var roles_form = $('#roles_form');
var error_roles_form = $('.alert-danger', roles_form);
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
debug: true,
rules: {
role: "required"
},
messages: {
role: "Please select a role."
},
errorLabelContainer: error_roles_form // puts the error messages into this container
});
HTML:
<form id="roles_form">
<div class="alert alert-danger vd_hidden"></div>
<input id="role_administrator" name="role" type="radio" value="administrator" />
<input id="role_manager" name="role" type="radio" value="manager" />
<input type="submit" value="Submit" />
</form>
DEMO: http://jsfiddle.net/TTJB7/1/
For all other available callback options, see the documentation.
When I realised that the actual problem is with the hidden radio elements, I did a little research and solved the issue.
First I applied ignore to "" so that it will not ignore hidden elements and validate them.
Then I need to stop default error message to appear after the element. So I assigned an empty function to that option.
Here is my final JavaScript code:
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
role: "required"
},
invalidHandler: function (event, validator) { //display error alert on form submit
error_roles_form.fadeIn(500);
},
errorPlacement: function(error, element) {}
});
I know how to validate a form using Semantic UI, and can even read in console the message "Form has no validation errors, submitting." However, where is this submitting to? I want to actually submit the form, but the way Semantic UI is laid out I don't seem to be able to specify where to submit to or anything.
I read this tutorial, but that uses Angular for submission and not just Semantic UI.
Am I missing something really simple here?
You can use jQuery's ajax:
//Get value from an input field
function getFieldValue(fieldId) {
// 'get field' is part of Semantics form behavior API
return $('.ui.form').form('get field', fieldId).val();
}
function submitForm() {
var formData = {
field1: getFieldValue('someId')
};
$.ajax({ type: 'POST', url: '/api/someRestEndpoint', data: formData, success: onFormSubmitted });
}
// Handle post response
function onFormSubmitted(response) {
// Do something with response ...
}
EDIT: also, you can use the onSuccess method of the form to run the submitForm function, ie when you initialize the form:
$('.ui.form').form(validationRules, { onSuccess: submitForm });
onSuccess will only be called when the 'Submit' button is clicked and the form is valid based on the rules you specify.
EDIT: If you want the regular HTML form behavior, you will need to add the semantic css classes to the form tag.
<form class="ui form" method="POST" action="/signup">...</form>
And then you set up the validation rules using jQuery. This will give you the default HTML form behavior, ie when you hit the submit button, it will make a POST request to /signup in the case above. If any of your rules trigger, the submit is prevented until there is no validation errors.
use the original submit button but add semantic button style:
<input type="submit" value="Submit" class="ui button" />
<input type="submit" value="Submit" class="ui teal button big"/>
Semantic UI has it's own API to submit form. for example:
$('.ui.form .submit.button')
.api({
url: 'server.php',
method : 'POST',
serializeForm: true,
beforeSend: function(settings) {
},
onSuccess: function(data) {
}
});
The easiest way is to retrofit a standard HTML form use the code below.
Start with a basic working standard HTML form with a submit button and this will take your values and post them to your form destination, returning the output below your form submit button.
Its a good time to double check you are successfully linking to jquery, semantic javascript and semantic css at this point.
Add class="ui form" to your form tag .
Add the javascript below.
.
$(document).ready(function() {
// validation
$('.ui.form').form({
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter an email'
}
]
}
},
{
inline: true,
on: 'blur',
transition: 'fade down',
onSuccess: validationpassed
});
// called if correct data added to form
function validationpassed() {
// Multiple instances may have been bound to the form, only submit one.
// This is a workaround and not ideal.
// Improvements welcomed.
if (window.lock != "locked") {
var myform = $('.ui.form');
$.ajax({
type: myform.attr('method'),
url: myform.attr('action'),
data: myform.serialize(),
success: function (data) {
//if successful at posting the form via ajax.
myformposted(data);
window.lock = "";
}
});
}
window.lock = "locked";
}
// stop the form from submitting normally
$('.ui.form').submit(function(e){
//e.preventDefault(); usually use this, but below works best here.
return false;
});
function myformposted(data) {
// clear your form and do whatever you want here
$('.ui.form').find("input[type=text], textarea").val("");
//$('.ui.submit.button').after("<div>Message sent. Thank you.</div>");
$('.ui.submit.button').after(data);
}
});
Basic form:
<form action="process.php" method="post" class="ui form">
<div class="field">
<label>title</label>
<input name="email" type="text">
</div>
<input type="submit" class="ui button"/>
</form>
If you want the error message to show in a box rather than within the form itself include this in your form, and remove the words "inline: true," and Semantic UI does the rest:
<div class="ui info message"></div>
NOTE: Using form tags with Semantic UI isn't strictly necessary as you only really need a div with the classes "ui form", however this retrofit code does require a form tag.
What if you don't wana use ajax?!
Use this one:
$( "#reg_btn" ).click(function(event){
event.preventDefault();
$('#register_form').submit();
});
in this case u can use <button> tag... there is no need to use classic tag instead
Semantic UI is based on jQuery and CSS so if you want to submit your form data you have some way to do that:
Send your form data with AJAX
Use some jqQuery plugins like this
Trick!
Put a submit button and set its display to none. When a user clicks on the div button throw that event to the submit button, in this way:
$("div_button_selector").on("click", function(){
$("input[type='submit']").trigger('click');
});
See post Adding errors to form validation doesn't work? for form and error validation. Since Semantic UI is a client side tool for user interface, this is the php for "self submitting / same code page" contact email. Since the purpose of Semantic UI is not logic processing, what language and or method do you want to use for form submission? JS/jquery client side or serverside php, rails, etc.? Keep in mind Semantic UI is dependent on jquery.
<?php
if (isset($_POST["email"]))
{
if ($_POST["email"] != "")
{
$from = htmlentities($_POST["email"]);
$subject = htmlentities($_POST["subject"]);
$message = htmlentities($_POST["message"]);
$message = wordwrap($message, 70);
mail("valid-server-email-username#valid-server-address", $subject, $message, "From: $from\n");
$_POST["email"] = "";
$_POST["subject"] = "";
$_POST["message"] = "";
unset($GLOBALS['email']);
header("location: /");
}
}
If you have a form like this
<div class="ui form segment">
<p>Tell Us About Yourself</p>
<div class="field">
<label>Name</label>
<input placeholder="First Name" name="name" type="text">
</div>
<div class="field">
<label>Username</label>
<input placeholder="Username" name="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="ui blue submit button">Submit</div>
</div>
you can use the foolowing script to send the form
$('.ui.blue.submit.button').on('click', function() {
submitForm();
});
function submitForm() {
var formData = $('.ui.form.segment input').serializeArray(); //or .serialize();
$.ajax({
type: 'POST',
url: '/handler',
data: formData
});
}
I've a form where I have rows to an table manually.
This row need and input (required) and have two select...
The problem is, if I add more than one row the submit validation for the table don't work for the second (and subsequent rows)...
Javascript code:
$('#classAdd').click(function(e){
e.preventDefault();
//trainingAction.addRow(schoolGroups[0].schoolGroupId, -1, '');
//add one line
$('#classes > tbody:last').append('<tr><td><input class="required datepicker classStartDate" name="classStartDate" /></td>'+
'<td><select class="classSchoolGroupId"></select></td>'+
'<td><select class="classSchoolId"></select></td>'+
'<td><i class="icon-remove"></i></td></tr>');
var last = $('#classes tr:last');
var csgi = last.find('.classSchoolGroupId');
var csi = last.find('.classSchoolId');
var input = last.find('.classStartDate');
//append values
trainingAction.appendArrayToSelect(csgi, schoolGroups, 'schoolGroupId', 'schoolGroupName', -1);
//append values
trainingAction.appendArrayToSelect(csi, schoolGroups[0].getSchools(), 'Value', 'Text', -1);
//add event
trainingAction.schoolGroupChange(csgi);
//rebind datepicker
helpers.bindDatepicker();
//rebind validators
$('form').validate();
$(input).rules('add', {
required: true
});
//rebind remove button
trainingAction.removeClass();
});
I try the code above like the suggested here (jQuery validate - group inputs with similar rules).
Another snippet that I try and don't work (based on this post jquery validation rules)
$('form').validate({
rules:{
classStartDate: {
required:true
}
}
});
Any suggestion to resolve this issue?
Thanks in advance!
EDIT:
jQuery version: 2.0
If you duplicate with the same name on the input only the first one is validated, you need to add the brackets to the name like this
<input class="required datepicker classStartDate" name="classStartDate[]" />
And the javascript
$('form').validate({
rules:{
"classStartDate[]": {
required:true
}
}
});
hope i can help in something