Check if an input with class is empty in a form - javascript

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/

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>

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

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>

Javascript - Validation returning false when correct condition is met

Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:
If error is found change text field background color to red, change field value to error message
If no errors are found, proceed
My problem
The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?
Code follows:
function validate(){
//form validation
var name=document.getElementById("name");
var surname=document.getElementById('surname');
//name
if (name.value=='') {
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name is required"
return false;
}
else if(isNaN(name)==true){
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name: Only enter letters A-Z"
return false;
}
//surname
if (surname.value == ""){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname is required"
return false;
}
else if(isNaN(name)==true){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname: Only enter letters A-Z"
return false;
}
return true;
}
HTML
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" id="name" value="Name" class="textbox" name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
<br />
<input type="text" id="surname" value="Surname" class="textbox" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number
isNaN(name.value)
Demo: Fiddle
You should use onsubmit event of form instead of click.
<form id="enquire" method="post" onsubmit="return validate()">

Remove unchanged input fields from Form while submit

In my web application I have edit profile page. In editprofile page their is many fields like
Name : <input type="text" name="name"/>
Location : <input type="text" class="geolocation" name="location">
Birthdata : <input type="date" name="dob">
Profile Picture : <input type="file" name="photo"/>
I want to send back the data of only the fields which are edited and not all the fields.
I'd normally do something like this on the backend.... but for your requirement you could remove the inputs that haven't changed. When you generate the html you can define an extra data attribute. Here's how I would do that:
HTML:
<form id="myform">
<input type="text" id="Name" data-initial="Foo" value="Foo" />
<input type="text" id="Location" data-initial="Bar" value="Bar" />
<input type="submit" value="Submit" />
</form>
JS:
$("#myform").submit( function() {
$(this).find("input").filter( function() {
$this = $(this);
return $this.data("initial") == $this.val();
}).remove();
});
http://jsfiddle.net/uLe7T/
I added an alert in the fiddle so you can see that they are removed before the form is submitted
jsFiddle
HTML
<input id="test" type="text" value="Some Text" data-value="Some Text">
JS
$('#test').blur(function() {
el = $(this);
if (el.val() != el.attr('data-value')) {
console.log('Edited');
} else {
console.log('Not Edited');
}
});

How to prevent form element from sending some fields we don't want?

I have a form element that contains about 5 fields which final query is going to create by processing values those fields. So I want to send only final query, not all of those, to the server. How can I exclude those fields from being submitted (using jQuery)?
<form action="abc/def.aspx" method="get">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="text" name="field3" />
<input type="text" name="field4" />
<input type="text" name="field5" />
<input type="hidden" name="final" />
<input type="submit" value="Send" />
</form>
Output of form submission looks like below:
abc/def.aspx?field1=val1&field2=val2&field3=val3&field4=val4&field5=val5&final=finalQuery
Remove the name attribute on the fields you do not want submitted to the server.
<form action="abc/def.aspx" method="get">
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="hidden" name="final" />
<input type="submit" value="Send" />
</form>
This is the simplest way to achieve what you want, and it works on all major browsers.
W3 spec talks about only submitting form values when name is present: http://www.w3.org/TR/html401/interact/forms.html#h-17.2
Remove the element on submit.
On the onsubmit handler:
$(formElement).submit(function() {
$(this.field1).remove(); //removing field 1 from query
return true; //send
});
Disabling the form element also stops it from being entered into the query.(tested on Chrome)
$(formElement).submit(function() {
this.field1.disabled = true;
return true; //send
});
I think the best solution is to handle the submit and then send the request yourself:
$(form).submit(function() {
//do everything you need in here to get the final result
var finalResult = alotoflogic();
$.get("abc/def.aspx",final=finalResult, "callbackfunction", "responseType");
return false;
});
that should do exactly what you want.
EDIT: as Alex pointed out this solution wouldnt send you to that page, just get the results if you need to go to the new page you can do:
$(form).submit(function() {
//do everything you need in here to get the final result
var finalResult = alotoflogic();
window.location('abc/def.aspx?final='+finalResult);
return false;
});
This way the browser is redirected to that page and only the final result is send.

Categories