Check if html form values are empty using Javascript - javascript

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.

Related

Javascript form validation return false error

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.

JavaScript validation change value on submit

I need to set a form input value to -1 when submitted if nothing is entered.
So far I have this function, but it doesn’t change the value to -1.
<form action="validate.php"
method="post" onsubmit="return validate()" >
<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
function validate()
{
var catID;
catID = document.getElementsByName("CategoryID");
if (catID.value == "")
catID.value = -1;
return true;
}
There are a number of issues with your code. First, JavaScript code should either be included in a separate javascript file or embedded inside script tags.
Second, you'll want to use return false instead of return true.
Also, the default behavior of a form, is for it to be submitted. You might want to pass in a parameter event and use the event.preventDefault method.
Also, getElementsByName returns a collection not a single element. You need to pass in an index like so
getElementsByName("categoryID")[0];
The form tag requires the closing tag </form>.
catID.value == "" is searching for an empty string. You can use a boolean instead. It's equivalent to !catID.value
Here is my temporary solution.
<form action="validate.php"
method="post" onsubmit="validate()" >
<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
</form>
<script>
var catID = document.getElementsByName("CategoryID")[0];
function validate() {
if (!catID.value) {
catID.value = -1;
return false;
}
}
</script>

IsNullOrEmpty attribute

In HTML exists
required
attribute, which force user to enter some date before submit. But user can type only spaces. Is there attribute which check is typed content is whitespace before postback. In need attibute which works similar to string.IsNullOrWhitespace in c#.
It took me a while to get the Regex right, but the following creates a rule to only select if there's no whitespace:
<input type="text" pattern=".\S*" />
As #Paul S. noted, this isn't checking the first character, so the following will do that:
<input type="text" pattern="^.\S*" />
Also, this does indeed only work in HTML5 browsers, but since the question contained required, I'm assuming there if is some fallback kept in mind.
Using the pattern attribute, you can make it accept only spaces
<form action="?" method="post"> <!-- required for snippet -->
<input type="text" required pattern="\s*"/>
</form>
However, please note that required prevents the submission of empty input (i.e. your "null"), so to permit that remove required so that pattern is doing the requirement checking
<form action="?" method="post"> <!-- required for snippet -->
<input type="text" pattern="\s*"/>
</form>
Lastly, still perform validation on the server as you can never assume a client is a safe source, or conversely, always assume the client is trying to hack you
If you can't assume HTML 5 support, you can shim the behaviour using JavaScript, which would look something like this for required
if(!('required' in document.createElement('input'))) {
window.addEventListener('submit', function (e) {
var form = e.target,
inputs = form.getElementsByTagName('input'),
i;
for (i = 0; i < inputs.length; ++i)
if (inputs[i].getAttribute('required'))
if (!inputs[i].value)
e.preventDefault(); // + warn?
});
}
and for pattern
if(!('pattern' in document.createElement('input'))) {
window.addEventListener('submit', function (e) {
var form = e.target,
inputs = form.getElementsByTagName('input'),
i,
re;
for (i = 0; i < inputs.length; ++i)
if (re = inputs[i].getAttribute('pattern')) {
re = new RegExp('^' + re + '$');
if (!re.test(inputs[i].value))
e.preventDefault(); // + warn?
}
});
}
You could also set useCapture to true for the listener to skip ahead in the queue of handlers, letting you prevent the event reaching other handlers in the case of submission prevented
<
<form onsubmit="alert('Submitted.');return false;"> <input type="text" required="" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" value="" name="dates_pattern2" id="dates_pattern2" list="dates_pattern2_datalist" placeholder="Try it out." autocomplete="off"> <input type="submit" value="»"> <datalist id="dates_pattern2_datalist"> </datalist> </form>

Html5 required validation checkbox

I made a input checkbox that contains array values. so it generates plenty of rows in a table.
But it needs for me to check it all to submit.
It doesn't allow me to check only few not all.
<form>
<table>
<td>
<input required="required" type="checkbox" name="id[]" id="id" value="<?php echo $result2["id"]; ?>"/>
</td>
<input type="submit" name="submit" value="submit"/>
</table>
</form>
How can i make the required field able to check atleast one and able to submit even if not all are checked?
I dont know if I understand you,
but maybee you need something like this:
Online demo
Main part with notes:
$('#frm').bind('submit', function(e) { // set this function for submit for your formular
validForm = true; // default value is that form is correct, you can chcange it as you wish
var n = $( "input:checked" ).length; // count of checked inputs detected by jQuery
if (n != 1) { validForm=false; } // only if you checked 1 checkbox, form is evaluated as valid
if (!validForm) { // if result of validation is: invalid
e.preventDefault(); // stop processing form and disable submitting
}
else {
$('#echo').html("OK, submited"); // ok, submit form
}
});
You can use any number of comboboxes under any tag and get count of selected by jQuery, then use any rule for validate form.

Javascript mini validation script

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>

Categories