how to check if input field is empty on submit [duplicate] - javascript

This question already has answers here:
Check if inputs are empty using jQuery
(22 answers)
Closed 9 years ago.
I'm using jQuery so i wonder how can i show error message after i click submit button only if an input field is empty.
Below the code my simple form how to apply to it.
<form id="myid" name="myid" method="post" action="hook.php">
name : <input type="text" name="name" id="name">
age : <input type="text" name="age" id="age">
<input type="submit" id="submit" name="submit" value="Save" />
</form>
I would like to show error like this

As someone has already mentioned, you should probably look to use an external library for validation. That said, this seems like it might work (see JSFiddle):
var $form = $("#myid"),
$errorMsg = $("<span class='error'>This field is required..!!</span>");
$("#submit").on("click", function () {
// If any field is blank, we don't submit the form
var toReturn = true;
$("input", $form).each(function () {
// If our field is blank
if ($(this).val() == "") {
// Add an error message
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
// If the field is not blank
else {
// Remove the error message
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});

You can use event.preventDefault to stop the default action happening. Then check your condition, display errors if the condition fails and submit the form if not.
$("#submit").click(function(event) {
event.preventDefault();
if($(this).val().length === 0) {
// display some error
} else {
$("#myid").submit();
}
});

Really I advice you to use some frameworks for form validation. Because that's the common task and it was already done 100000 times before. There are plenty of it, for example Parsley or Jquery plugin, but there are a lot of others which is simple and easily maintainable, just google 'javascript form validation'
Why is already implemented code better than custom in that case: 1) It already written, tested and working, 2) You almost never need only single validation, and really to validate form for several parameters could be a challenge and could lead to a big amount of validation code 3) framework is DRYer and a really a lot of other stuff.

I also advise you to use validation framework because you need more validation for different field. Use MooTools Floor this is most reliable framework for validation.
MooTool Floor

You can use the HTML5 required='required' option in the input tag...

Related

Form onsubmit() does not function

I want to control my form for the required input texts, and I have made a function in javascript. But when I click the button, and I havent fill the required field nothing the message do not appear, and I can go to the other page.
the function is:
function Validate(){
// create array containing textbox elements
var inputs = [document.getElementById('firstname1')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
and the part of form is:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#">
<input type="submit" value="Proceed" id="submit1" onclick="displayform2()" class="button" style=" margin-top: -40px;margin-left: 60%;width: 25%" disabled>
I have noticethat if I put off the onclick method in the button it works, but I should have this method at the button...How can I solve this?Please help me
function displayform2() {
/*For desktop*/
if (document.getElementById('desktop1').style.display=='block') {
document.getElementById('desktop1').style.display='none';
document.getElementById('desktop2').style.display='block';
document.getElementById('desktop3').style.display='none';
}
/*For mobile*/
if (document.getElementById('mobile1').style.display=='block') {
document.getElementById('mobile1').style.display='none';
document.getElementById('mobile2').style.display='block';
document.getElementById('mobile3').style.display='none';
}}
It opens another form in the page...so when I click the button the first form dissapeared and the second form is displayed
You have this: var inputs = [document.getElementById('firstname1')];
Then you try to loop through that. I'm betting firstname1 is a field, so it's either null (if that field doesn't exist) or an array with only one element (the field). It looks like you are trying to check all required fields, so that won't work.
I'm not 100% what you ultimately want to do, but it will likely be much easier if you use a framework like jQuery; otherwise, you are going to have to do some complicated case-handling for different browsers.
Nowhere in your code do you call submit. That is why the function in the onsubmit handler is not triggered. If you want the button to submit the form, it would need to be a submit button.
Your example is a little unclear. For example, you are trying to validate whether a value has been entered into the input "firstname1", but you don't have markup for that element in your HTML.
I suspect what you are trying to do is to validate whether the form has been filled out or not. Something like the following (which validates input "firstname1") will do the job:
$(document).on("click", "#submit1", function(){
if($("#firstname1").val() == "" || $("#firstname1").val() == null){
alert("Please complete all fields.");
}
});
Working example here
The above requires jQuery, but can also be converted into vanilla JavaScript.
Load the jQuery library in the "head" section of your document by including the following code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

genvalidator: check for checkbox in form validation

I'm using genvalidator to have some tests on input fields in a form. Problem is I can't find a way to test if a checkbox has been checked. This is how all the fields are set:
frmvalidator.addValidation("name","req","Insert your name");
frmvalidator.addValidation("city","req","Insert your city");
frmvalidator.addValidation("phone","req","Insert your phone number");
This is my checkbox
<input type="checkbox" name="agree" id="agree "value="yes"/>
How can I make it mandatory with genvalidator?
This is the part that handles the form process (in short: if there aren't errors, it's ok):
if(empty($name)||empty($city)||empty($phone)||BLAHBLAH)
{
$errors .= "\n Mandatory field. ";
}
if(empty($errors))
{
// send the email
}
It tried with this JS code with no luck:
function validate(form) {
if(!document.form1.agree.checked){alert("Please check the terms and conditions");
return false; }
return true;
}
If possible I'd like to use genvalidator functions. :)
You are expending a lot of energy trying to make the javascript plugin work.
Would you consider working with jQuery? If you haven't yet kicked its tires, it's a lot easier than it sounds -- and much more uniform / faster to type than plain js.
To use jQuery, you only need to include the jQuery library in the document, usually in the head tags thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Then, you can easily create you own verification routines, with FULL control over what you are doing.
Here is a working example for you to study. As you can see, the code is pretty minimal.
When the Submit button (#mysub) is clicked, we quickly check each field to see if it validates. If any field fails validation, we can return control to the user with the field colored and in focus.
If all fields pass validation, then we issue the submit() method on the form ID, and off it goes (to the location specified in the action="somepage.php" attribute).
Note that I added some quick/dirty code at bottom to remove any css colorization from failed validations. This code runs every time a field is exited, regardless whether the field has validation coloring or not. This is not very efficient (although it certainly won't hurt anything) and is only intended to demonstrate what is possible.
Hmmmmm. I think it would be more efficient to have a class with certain attributes, and add/remove that class if fail validation. Okay, I liked that idea enough that I created a new jsFiddle using that method to demonstrate what that would look like.
jsFiddle here
HTML:
<form id="fredform">
First Name: <input id="fname" name="fname" type="text"/>
Last Name: <input id="fname" name="fname" type="text"/>
Email: <input id="fname" name="fname" type="text"/>
<input id="mysub" type="button" value="Submit" />
</form>
jQuery:
arrValidate = ['fname','lname','email']
$('#mysub').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed the [' +nextFld+ '] field.');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#fredform').submit();
});
//Remove any css validation coloring
$('input:not([type=button])').blur(function(){
$(this).css({'border':'1px solid lightgrey','background':'white'});
});
Note that there is also a jQuery validation plugin that looks very professional. I haven't played with it myself, always preferring to code my own stuff, but here is the link:
http://jqueryvalidation.org/documentation/
Note the very cool demo
Just so you know what to expect: implementing this plugin would be more difficult than the methodology I suggested above.
` ANSWER TO YOUR COMMENT QUESTION: `
Regarding your comment and the code posted at pastebin:
(Sorry for the long answer, but I want it to be clear. Please read carefully.)
(1) Please wrap your javascript code in a document.ready function. This is my fault; I should have added it to my code example. Otherwise, the code will execute before the DOM fully exists and event triggers will not be bound to the controls (because they do not yet exist in the DOM). Therefore:
arrValidate = ['checkbox']; //a global variable
$(document).ready(function() {
$('#submit').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed [' +nextFld+ ']');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#contact_form').submit();
}); //END #submit.click
}); //END document.ready
(2) Your checkbox still has the value="yes" attribute that breaks the javascript. Please change this:
<input type="checkbox" name="checkbox" id="checkbox" value="yes" /> <small>Ho
to this:
<input type="checkbox" name="checkbox" id="checkbox" /> <small>Ho
(3) There is no need to have type="submit" for your <input value="Invia"> button, nor is there a need for a name= attribute on that control.
First the name= attribute: it is only useful when passing data from that control to the PHP(?) file that processes your form: ($_SERVER['SCRIPT_NAME']). The name= part is the variable name, and the value of the control is the variable value. The button has no data to pass along, so does not need to have a variable name assigned to it.
Next, the type="submit": This is not required, because you can use jQuery to submit the form any time you want. In the old days, before javascript/jQuery, we had forms. Back in those days, the only way to make the form submit was to use the type="submit" attribute. There was no such command as: $('#myFormId').submit(); -- but today there is. So change that attribute to type="button" and let jQuery submit the form for you. Trust me, this works!
Another thing to consider: once you use type="submit" you must deal with the form's default actions when clicking that button. You cannot simply return control to the user when there is an error, because the form has been told to submit. (You must use event.preventDefault() to override the default behaviour -- you can read about that later.)
(4) Checkbox values must be checked using one of these methods. Checkboxes do not have a value. This is my fault again, I should have written a checkbox into my example.
$('#submit').click(function() {
var nextFld, i ;
//Validate the checkbox:
if ( $('#checkbox').is(':checked') == false ) {
alert('You must read the informativa and check the checkbox at bottom of form');
return false;
}
//Validate the rest of the fields
for (i=0; i<arrValidate.length; i++){
(5) jQuery's submit() method won't work IF any element uses =submit as either its name= or id= attribute.
This is a weird thing, but you need to know it. I just learned it (again) while troubleshooting my jsFiddle example.
If you want to use jQuery to submit your form (and we do) via the .submit() method, then no element in your form can have the name= or id= attribute set to "submit". The INPUT button had both name= and id= set to submit; that is why it wasn't working.
Reference: http://blog.sourcecoder.net/2009/10/jquery-submit-on-form-element-does-not-work/
See the revised code example in the jsFiddle:
Revised jsFiddle here
Please Please Please study the above jsFiddle. You should be able to dump the genvalidator plugin entirely. If you understand the jsFiddle completely, you will be in a new place as a programmer.
If you're using jQuery, try checking this way:
function validate(form) {
if(!$('[name="agree"]').prop('checked')){
alert("Please check the terms and conditions");
return false;
}
return true;
}
or try using
function validate(form) {
if(!$('[name="agree"]')[0].checked){
alert("Please check the terms and conditions");
return false;
}
return true;
}
This is untested but I think it would look something like this:
function DoCustomValidation() {
var frm = document.forms["myform"];
if(document.form1.agree.checked != true) {
sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
return false;
}else{
return true;
}
}
Note that you must customize this line to have the correct name of your own form:
var frm = document.forms["myform"];
Plus, you also need to associate the validation function with the validator object:
frmvalidator.setAddnlValidationFunction("DoCustomValidation");
Source: genvalidator documentation
Since you've tagged the question with JQuery, this should work for you:
function validate(form) {
if ($("#agree :checked").length < 1) {
alert("Please check the terms and conditions");
return false;
}
return true;
}
I tend to use this approach because it also works for multiple checkboxes or radio button groups as well. Note, however, that it does not care about what was checked, just that something was checked . . . in the case of a single checkbox, this acts as a "required to be checked" validation as well.
Add a new div for error location above your input tag like this :
<div name="formname_inputname_errorloc" class="errorstring">
//<your input tag goes here>
Make sure u have the css for errorstring class in your css file. and the other req js files
Try to search the demo for gen validator it has been totally explained in the demo
frmvalidator.addValidation("agree","selmin=1","Please select checkbox");

How to manually show an HTML validation message from a JavaScript function?

I want to know if there is any way to programmatically show a HTML validation error, using a JavaScript function.
This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.
I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).
JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/
HTML Form:
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>
JavaScript:
function triggerCustomMsg()
{
document.getElementById("email").setCustomValidity("This email is already used");
}
The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.
You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.
var applicationForm = document.getElementById("applicationForm");
if (applicationForm.checkValidity()) {
applicationForm.submit();
} else {
applicationForm.reportValidity();
}
reportValidity() method will trigger HTML5 validation message.
This question was asked over a year ago, but it's a good question that I recently encountered as well...
My solution was to use JavaScript to create an attribute (I went with "data-invalid") on the <label> of each <input>, <select> and <textarea> containing the validationMessage.
Then some CSS...
label:after {
content: attr(data-invalid);
...
}
... displays the error message.
Limitations
This only works provided each element has a label. It will not work if you put the attribute on the element itself, because <input> elements cannot have :after pseudo elements.
Demo
http://jsfiddle.net/u4ca6kvm/2/
As mentoned by #Diego you can use form.reportValidity();
To support IE and Safari include this polyfill, it just works:
if (!HTMLFormElement.prototype.reportValidity) {
HTMLFormElement.prototype.reportValidity = function() {
if (this.checkValidity()) return true;
var btn = document.createElement('button');
this.appendChild(btn);
btn.click();
this.removeChild(btn);
return false;
}
}

jQuery Validate Plugin - Validate Hidden Field by Name

Primary Question
I'm new to the jQuery validate plugin. I need to validate hidden fields that are being added and removed dynamically and that share the same name. Example markup:
<input type="hidden" name="hdnItemID" value="123" />
<input type="hidden" name="hdnItemID" value="987" />
Basically, I need to know if any elements exist that have the name hdnItemID. If they exist, the validation should be successful, else, the validation should fail.
if($("input[name='hdnItemID']").length > 0) {
//Form is valid
}
else {
//Form is invalid
}
I've looked at a few questions that seem close, but they don't seem to fit the bill. Any suggestions?
jQuery Validate Plugin - How to create a simple custom rule?
jquery validate - valid if hidden field has a value
Secondary Question
Assuming that what I'm asking is possible, how would I specify where the validation message is displayed? Currently, I'm placing an asterisk by each required element when the validation fails. I'd like to continue to do that, but place the validation message for the hidden fields by the submit button.
Use submitHandler event of the plugin to check if the hidden field exists or not. You can then conditionally submit the form. Try this.
$(function() {
$('#form1').validate({
submitHandler: function(form) {
if($("input[name='hdnItemID']").length > 0) {
//Form is valid
form.submit();
}
else {
//Form is invalid
alert('form data invalid');
}
}
});
});

Using depends with the jQuery Validation plugin

I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.

Categories

Resources