I'm new to js. trying to create mini validation function which will check fields if they're empty or not.
What i wanna do is, to call func like that checkIfEmpty("fullname, email,..."), then inside function, check each field seperated by comma, collect empty fields to one array, and check at the end if this array is empty or not. Tried something like following func, but don't know all alternatives of php functions in js. Please help me to realize my idea..
function checkIfEmpty(fields)
{
var emptyFields=new Array();
fields=fields.split(',');
foreach(fields as field)
{
if (!field.val()) {
field.attr('class', 'invalid');
emptyFields[] = field;
}
}
if(emptyFields.length()==0){return true;}
else {return false;}
}
Seems like you want something like this:
$("input:text").each(function(i, field) {
if (!field.val()) {
field.addClass('invalid');
}
});
return ($("input.invald").length > 0); // return true if invalid fields
You could also set a class on each input that not suppose to be empty, then on form submission check each input that has this class.
$('#form_id').submit(function() {
$('.required').each(function() {
// if a input field that's required is empty
// we add the class '.invalid'
if(!$(this).val()) {
$(this).addClass('invalid');
}
});
// prevent the submission if number
// there is required fields still empty
return ($('input.invalid').length == 0);
});
This is an example form with one required field called email:
<form method="POST">
<input type="text" name="email" class="required" />
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="submit" value="SEND" />
</form>
Related
The idea is that when the user is presented with the What is your name box, if they don't fill it in they would get a pop up message saying "please enter your name".
I don't understand why the form does not return the pop-up as I am calling the correct getElementsByName method I believe and checking if a value has been entered. I have tried changing the elementsByName to ("name") and ("UserInfo") but nothing happens. Does anyone have any ideas what might be the issue? I know the submit button is missing from the form but that was intentional as otherwise I'd have to post more code than necessary.
The code snippet is attached. The function name in html is called validate();
ALSO, I CANNOT MAKE ANY CHANGES TO THE HTML, IT NEEDS TO REMAIN AS IS.
function Validate() {
alert(document.getElementsByName("UserInfo")[0].value);
if (name == "" || name == null) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" />
</div>
</fieldset>
You are checking for name to be empty or null but the variable name isn't defined hence its always executing the else part.
Below is the working model of your snippet.
I had assigned the input value to value and check for existence, do alert if not a valid input.
function Validate(){
const value = document.getElementsByName("UserInfo")[0].value;
if(!value) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<form onsubmit="Validate()">
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" required />
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
UPDATE:
Use required attribute.
Even better approach would be to wrap all the elements and submit button inside form and add required attribute to all required elements. Updated the answer.
Adding required will abort the submit itself.
I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.
I have two input fields one is file the other is textarea
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
User has to either upload a file or type text. If the user leaves blank both of the inputs, it should say like "choose a file or type info" if he/she fills both, it is ok.
My JQuery:
$(function(){
$(".input_field").prop('required',true);
});
I have this code. How can we implement something like if else condition to make it required one of the fields?
See this fiddle https://jsfiddle.net/LEZ4r/652/
I modified your code to each all the elements with a class of input_field when the form is submitted.
$(function(){
$('form').submit(function (e) {
var failed = false;
$(".input_field").each(function() {
if (!$(this).val()) {
failed = true;
}
});
console.log(failed);
if (failed === true) {
e.preventDefault();
}
});
});
Based on your question, there are only two possible conditions:
if either one field or both fields are filled, user passes validation
if no fields are filled, user fails validation
This can be easily done by checking for the value of either input. As long as one is not empty, user passes the test. This if/else condition can be written as:
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
// Passed validation
} else {
// Failed validation
}
A simple pattern to check for errors is to create an error flag, which will be raised when one or more validation checks have failed. You evaluate this error flag at the end of the script before manual form submission:
$(function(){
$('form').on('submit', function(e) {
e.preventDefault();
// Perform validation
var error = false;
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
alert('Passed validation');
error = false;
} else {
alert('Please fill up one field');
error = true;
}
// Check error flag before submission
if(!error) $(this)[0].submit();
});
});
See working fiddle here: http://jsfiddle.net/teddyrised/LEZ4r/653/
Check inside your form If atleast one is done break the loop and go for submit else return false
$(function(){
$('form').on('submit',function(e){
var doneOnce = false;
$(this).children().each(function(){
if($(this).val()){
doneOnce = true;
return false;//return false will break the .each loop
}
});
alert(doneOnce)
if(!doneOnce){
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
<input type=submit />
</form>
You can write codes in Javascript to validate form. You have to make an onclick or onsubmit function, and the function will check whether any of the input field is empty. You can write something like the following code:
<script>
function validateForm() {
var fstname=document.getElementById("fname").value;
var lstname=document.getElementById("lname").value;
if(fstname===null || fstname===""){
alert("Plese choose a file.");
return false;
}
else if(lstname===null || lstname===""){
alert("Plese type file info.");
return false;
}
else{
return confirm("Your file: "+fstname+" and it of type "+lstname);
}
}
<body>
<form action="text.php" name="myForm" onsubmit="return validateForm()">
First Name: <input type="file" id="fname" name="FirstName">
Last Name: <input type=text" id="lname" name="LastName"><br/>
<input type="submit" value="Submit">
<form>
</body>
I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.
I'm making a validation form like so:
<form id="registerform" method="post" onsubmit=return checkformdata();>
<input type="text" name="fname" value=""/>
<input type="text" name="lname" value=""/>
<input type="checkbox" name="privacy" value="1"/>
</form>
checkformdata() Validates only the first name and last name for the checkbox field, which is done using jQuery.
Here is the code that I tried:
jQuery(document).ready(function() {
// Handler for .ready() called.
jQuery('#registerform').submit(function() {
if (!jQuery("#privacy").is(":checked")) {
alert("none checked");
return false;
}
});
});
It is also working but the alert field is comes twice for example firstname is empty then alert for first name and alert for checkbox comes up. I want to show the alert for the checkbox after the checkformdata(); function. Is it possible to give the priority first for javascript then the jquery validation.
Thanks in Advance.
You should only have one functions, which is the second method you are using. Both functions are called now, which is not wat you want. Also, you can use $ instead of jQuery.
Dont use return false! Unless you know what you are doing. Use preventDefault():
$('#registerform').submit(function(event) {
var errorString = [];
// START VALIDATION
if ($("#privacy").is(":checked") ) {
errorString.push("none checked"); // Save for later
}
if ($('[name="fname"]').val).length===0) {
errorString.push("No firstname"); // Save for later
}
if ($('[name="lname"]').val).length===0) {
errorString.push("No lastname"); // Save for later
}
// CHECK IF ERRORS ARE FOUND
if( errorString.length !==0){
event.preventDefault(); // stop the submitting
// Do whatever you like with the string, for example;
alert( "Something went wrong: \n"+errorString.join("\n") ); // alert with newlines
}
// NO ERRORS FOUND, DO SOMETHING
else{
// all good. Do stuff now
}
});