Parsley.js Validation if 1 of 4 Fields Has a Value - javascript

On a form there are 4 text inputs.
If at least 1 of them has a value then all remaining fields must have a value.
Is it possible to configure Parsley.js for this validation?

Yes, it is possible. However, there is no default configuration to do it.
This means that you must create that logic in your javascript and destroy / bind parsley in each case.
Take a look at this code (jsfiddle available):
<form class="form-inline" method="post" id="myForm">
<input type="text" id="field1" name="field1" />
<input type="text" id="field2" name="field2" />
<input type="text" id="field3" name="field3" />
<input type="text" id="field4" name="field4" />
<button type="submit" class="btn btn-default">test</button>
</form>
<script>
$('#myForm').parsley();
$("#field1, #field2, #field3, #field4").on('change', function() {
if ($("#field1").val().length > 0 ||
$("#field2").val().length > 0 ||
$("#field3").val().length > 0 ||
$("#field4").val().length > 0 )
{
// If any field is filled, set attr required
$("#field1, #field2, #field3, #field4").attr("required", "required");
} else {
// if all fields are empty, remove required attr
$("#field1, #field2, #field3, #field4").removeAttr("required");
}
// destroy ParsleyForm instance
$('#myForm').parsley().destroy();
// bind parsley
$('#myForm').parsley();
});
$("#myForm" ).on('submit', function( event ) {
$(this).parsley().validate();
if ($(this).parsley().isValid()) {
alert('form is valid');
}
event.preventDefault();
});
</script>

Related

Check if all the required inputs are set before submit with javascript

I'm wondering if there's a way to force a check for the required inputs on a form before submitting it programmatically using pure Javascript:
<form method="post" action="myController.php" id="myForm">
<input type="text" id="input1" required>
<input type="text" id="input2" required>
<input type="text" id="input3" required>
<input type="submit" onClick="return checkForm(event)" value="Save">
</form>
My Javascript file:
function checkForm(e) {
e.preventDefault();
// Some other stuff
/*Prevalidate required inputs here*/
document.getElementById('myForm').submit();
}
I'm wondering if there's something like:
if(document.getElementById('myForm').valid()) {
document.getElementById('myForm').submit()
}
Where the required inputs are checked just before submitting the form without the need to verify one by one directly by code.
There is the form.onSubmit event
But if you are using HTML 5, you can use input.pattern with a regular expression; submission will be blocked if the input doesn't pass the check and the input element will (on many browsers) get a red border around it.
If you need to do something custom on submit you can trigger validation via form.reportValidity() and get back a boolean indicating whether all inputs have satisfied their constraints.
You can also listen for invalid events that will get fired for each invalid input during validation if you want to do something to flag them in the UI:
function onInvalid (e) {
e.target.classList.add('invalid');
}
const form = document.querySelector('form');
document.querySelectorAll('input').forEach(input => {
input.addEventListener('invalid', onInvalid);
});
form.addEventListener('submit', (e) => {
e.preventDefault();
const valid = form.reportValidity();
})
.invalid {
border: 4px solid red;
}
<form>
<input name="test1" required />
<input name="test2" required />
<input name="test3" required />
<input type="submit" />
</form>
Take adventage of Form attribute onsumbit to submit the form if the value returned from the function checkForm which returns boolean value if all fields are filled and not empty dynamically.
function checkForm(e) {
let valid = true;
inputs = document.querySelectorAll('[type="text"]')
for(input of inputs){
if(input.value.trim()==''){
valid = false;
break;
}
}
return valid;
}
<form method="post" id="myForm" action='test.php' onsubmit="return checkForm(this)">
<input type="text" id="input1" required>
<input type="text" id="input2" required>
<input type="text" id="input3" required>
<input type="submit" value="Save">
</form>

Disable button unless specific fields have values

I have an ASPX form and I need to disable the submit button if any one of six specific fields are empty. I'm trying to do this via Javascript or jQuery, but so far I can only find examples of either a single field on the form being empty, or ALL fields on the form. In my case, I don't care about several fields - only the six specific ones.
So basically, I have six conditions and one action. I found one example, but it was stringing together six different IF statements. I'd like to find a more streamlined way if possible. So, for example, I might do THIS for a single field... but how to do it for field2, field3, field4, etc. as well?
$(document).ready(function(){
$('#submit_btn').prop('disabled',true);
$('#field1').keyup(function(){
$('#submit_btn').prop('disabled');
})
});
Using Javascript or jQuery, what's the most efficient way to disable an input button if any of six input fields is blank?
You can add the same class name to all the elements and then do a validation foreach class element. Like in below code, i added the same class name to all the input for which the validation is required using class="valid" and then use the jquery class selector and the keyup method that you used to control the state of the button.
(function() {
$('.valid').keyup(function() {
var isEmpty = false;
$('.valid').each(function() {
if ($(this).val() == '') {
isEmpty = true;
}
});
if (isEmpty) {
$('#button1').attr('disabled', 'disabled');
} else {
$('#button1').removeAttr('disabled');
}
});
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
1<input type="text" class="valid" /><br />
2<input type="text" class="valid" /><br />
3<input type="text" class="valid" /><br />
4<input type="text" class="valid" /><br />
5<input type="text" class="valid" /><br />
6<input type="text" class="valid" /><br />
<input type="button" id="button1" value="Test Me!" disabled="disabled" />
</form>
If your requirements will allow it, you can use HTML 5 field validation. The browser will not allow the form to submit.
<form>
<label for="choose">Foo</label>
<input name="bar" required>
<input type="submit" /> <!-- <--- This will generate an error message if the user clicks it when the field is empty -->
</form>
You have the start of it correct; create an array with six variables, one for each of the fields, and create a new function to validate everything that is called on each keyup. So you would have
var[] array
$('#field1').keyup(function() {
array[0] = $('#field1').val();
validate();
}
${'#field2').keyup(function() {
array[1] = $('#field2').val();
validate();
}
...create one each for each field
function validate() {
for (var i = 0; i < array.length; i++) {
if(!arrays[i]) {
$('#submit_btn').prop('disabled');
return;
}
}
$('#submit_btn').prop('enabled'):
}
What this does is it listens to the fields for changes and updates the array. A blank value is falsy so you can just go through the array and disable the button if it's blank or null or something. Break out of the for loop in that case; you don't care about whatever else. If nothing disables the button and breaks the for loop then it's valid and the button is enabled.
This approach is useful because it's easily extendable. You can just push extra things into the array if you want to check them without rewriting the validation function.
This assumes you do not want to just use standard form validation and do it manually.
Add a common class to each of the required inputs. Then check the length of that object against the length of a filtered object where value is not empty. Then you can use that condition to set the prop value of the button to true/false.
http://api.jquery.com/filter/
JQuery:
$('form .required-valid').on('input paste change', function() {
var $required = $('form .required-valid');
//filter required inputs to only ones that have a value.
var $valid = $required.filter(function() {
return this.value != '';
});
//set disabled prop to false if valid input count is != required input count
$('#submit_btn').prop('disabled', $valid.length != $required.length);
});
HTML:
<form>
<label>Field1</label>
<input type="text" id="field1" class="required-valid" />
<label>Field2</label>
<input type="text" id="field2" class="required-valid" />
<label>Field3</label>
<input type="text" id="field3" class="required-valid" />
<label>Field4</label>
<input type="text" id="field4" class="required-valid" />
<label>Field5</label>
<input type="text" id="field5" class="required-valid" />
<label>Field6</label>
<input type="text" id="field6" class="required-valid" />
<label>Field7</label>
<input type="text" id="field7" class="not-required" placeholder="not required" />
<button id="submit_btn" disabled>
Submit
</button>
</form>
Example:
https://jsfiddle.net/SeanWessell/q2msc80L/
$(document).ready(function() {
$('#submit_btn').prop('disabled', true);
$('#field1').keyup(function() { // on keyup
var value = $(this).val(); // retrieve the value of the input
if (value.length == 0) // if the value's length is 0 (empty)
$('#submit_btn').prop('disabled', true); // disable the button
else // if not
$('#submit_btn').prop('disabled', false); // enable it
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="field1"/>
<input id="submit_btn" type="submit"/>
</form>
Just note that the form can be submitted using enter key, so instead of checking on every keyup, it would be better if you check onsubmit instead.

Check if an input with class is empty in a form

I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.
If all the inputs in the form were required I could have used something like
$('#subButton').on('click', function(e) {
if (!$('#formName').val()) {
e.preventDefault();
alert("Fill all the required fields");
});
But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs.
Something like:
$('#subButton').on('click', function(e) {
if (!$('#formName.req').val()) {
e.preventDefault();
alert("Fill all the required fields");
}
});
In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.
Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?
var hasEmptyFields = $('#formName.req').filter(function() {
return this.value.replace(/^\s+/g, '').length; //returns true if empty
//Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0
if (hasEmptyFields) {
}
Use reduce
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
if (!submitAllowed) { ... }
Here is a simple demo:
<form action="dummy.asp" onSubmit="return handleSubmit()">
<p> You can only submit if you enter a name </p>
<br />
Enter name: <input class="req" type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function handleSubmit() {
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
return submitAllowed;
}
</script>
But since in my form there are required inputs (with class="req")
and non required inputs, I would like to know if there's a method to
perform the check only on the .req inputs
There is an HTML5 form boolean attribute required.
required works on:
<input type="text" />
<input type="search" />
<input type="url" />
<input type="tel" />
<input type="email" />
<input type="password" />
<input type="date" />
<input type="number" />
<input type="checkbox" />
<input type="radio" />
<input type="file" />
Example:
input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>
Peculiarly, the StackOverflow Snippet above doesn't seem to be working.
Here's a JSFiddle to demonstrate what it should be doing:
https://jsfiddle.net/a5tvaab8/

How to fire a custom event to trigger partial form validation?

Iam trying to validate my form step by step on clicking a button called 'next'.
Is there a way to fire a custom event to trigger partial form validation?
Something like that:
<input type="text" id="age-id" name="age"
ng-model-options="{updateOn: 'ValidateStepOne'}"
min="18"
max="99"
ng-model="data.age"
>
Triggering the event onclick at a button:
$scope.validate = function() {
$rootScope.$broadcast('ValidateStepOne');
};
Any help would be kindly appreciated.
Kind regards
OliverKK
I was separating the huge form into sub forms(thanks to #fiskers7), which is pretty handy.
The validation takes place by using a custom trigger on clicking at the
next button to validate the current step.
The required validator and other used validators will be executed when the custom submit event is fired.
<form id="form1" ng-submit="validate(1)" ng-model-options="{ updateOn: 'submit' }" novalidate>
<input type="text" ng-model="name" required>
<span ng-show="form1.$submitted && form1['name'].$error.required">Name is required!</span>
<input type="submit" value="next">
</form>
<form id="form2" ng-submit="validate(2)" ng-model-options="{ updateOn: 'submit' }" novalidate>
<input type="text" ng-model="surename" required>
<span ng-show="form2.$submitted && form1['surename'].$error.required">Name is required!</span>
<input type="submit" value="next">
</form>
The validation function submit within the controller looks like this:
$scope.validate = function(num) {
$scope['form' + num].$setSubmitted(true);
if (!$scope['form' + num].$valid) {
$scope.scrollToTop();
} else if (num < $scope.maxSteps) {
$scope.next(num + 1);
} else {
$scope.submit();
}
}
See the AngularJS Documentation for more details:
https://docs.angularjs.org/guide/forms
Kind regards
OliverKK
You can separate your form into several pieces that use ng-if to decide whether to show them or not.
<form action="" name="myForm">
<div ng-if="step == 1">
<input type="text" required="true" name="input1" ng-model="inputVal1"/>
</div>
<div ng-if="step == 2">
<input type="text" required="true" name="input2" ng-model="inputVal2"/>
</div>
</form>
see example.

jquery find input before button

I have a single form on the page and I have some jQuery to make sure that the inputs have been completed before the submit.
But now I need to have multiple similar forms repeated on the page and I need to change the jQuery to only check the two inputs in the form that the button was clicked and not check any other form on the page.
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
The jQuery that I have used previously to check on form using ID
// validate signup form on keyup and submit
jQuery('#submitDates').click(function () {
var found = false;
jQuery("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && jQuery(name).val()=='') {
alert ('Please choose your arrival and departure dates!')
found = true;
} ;
});
return !found;
});
.prev( [selector ] )
Returns: jQuery
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
This is quite short and will target any input displayed just before a button :
$("button").prev("input")
jsFiddled here
you can try like this:
CODE
jQuery('.submitDates').click(function () {
var found = false;
jQuery(this).siblings("input").each(function (i, name) {
// Check if field is empty or not
if (!found && jQuery(name).val() == '') {
alert('Please choose your arrival and departure dates!')
found = true;
};
});
return !found;
});
assuming your inputs are siblings for the button. Note I also changed button's id into class.
FIDDLE http://jsfiddle.net/FY9P9/
Closest and Find do it as well, wherever the input are for the button :
HTML:
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
JS:
$(".button").each(function () {
$(this).click(function () {
if (($(this).closest(".form").find(".toDate").val() == "") || ($(this).closest(".form").find(".fromDate").val() == "")) {
alert("Please fill in arrival and departure Date");
}
})
})
http://jsfiddle.net/GuqJF/1/

Categories