validation of form inputs in JavaScript - javascript

I want to validate a input fields of form in javascript. I have searched a lot on net and always got different ways to do it. It was so confusing. I want for every single input if it is left empty an alert should popup. Here is my code
<form method="post" action="form.html" id="FormContact" name="frm">
<p>Full Name: <br /><br /> <input type="text" name="FullName" size="50" id="Name"></p>
<span id="error"></span>
<p>Email:<br /><br /> <input type="email" name="Email" size="50" id="Mail"></p>
<p> Subject:<br /><br /> <input type="text" name="subject" size="50" id="Subject"></p>
Message:<br /><br />
<textarea rows="15" cols="75" name="Comment" id="text">
</textarea> <br /><br />
<input type="submit" value="Post Comment">
</form>
I got it done sometimes but that only worked for Full Name field.
Thanks and regards,

You can do something like this, to have an alert popup for each empty input.
$('form').on('submit', function(){
$('input').each(function(){
if($(this).val() === ""){
alert($(this).attr('name') + " is empty");
}
});
});

http://www.w3schools.com/js/js_form_validation.asp
if you're willing to use javascript, this would be pretty easy to implement.

use jquery validation plugin.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script>
$("#FormContact").validate({
rules: {
FullName: {
required:true
}
},
messages:{
FullName:{
required:"Please Enter FullName."
}
}
});
</script>

USE submit method of jquery the use each loop to validate the controls
LIVE CODE
$('form#FormContact').submit(function(){
var i= 0;
$('input').each(function(i,j){
if($(this).val() == "" || $(this).val() == undefined){
alert('empty');
i++;
}else{
i=0;
}
})
if(i == 0){
return false;
}else{
return true;
}
})

Related

Save HTML user input to Javascript variables

I'm testing the waters with HTML/CSS/Javascript. I have a (moderately) firm grasp of the three languages separately, it's just trying to get them to cooperate with each other that is giving me issues.
My CSS and Javascript files are linked externally to my HTML file.
I'm trying to get Javascript to save user input in a variable and show the text in an alert window.
function saveUn() {
var username = document.getElementById('un').value;
alert(username);
}
<form>
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" onclick="saveUn();" />
</form>
Any help is greatly appreciated!
UPDATE: It turns out my problem was, in fact, that I didn't insert my external Javascript file correctly. I fixed it, and now my code works just fine. Typos ruin lives, kids.
try with event.preventDefault();
function saveUn(event) {
var username = document.getElementById('un').value;
alert(username);
event.preventDefault();
}
<form>
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" onclick="saveUn(event);" />
</form>
Let your callback return false and pass that on to the onclick handler:
<form>
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" onclick="return saveUn();" />
</form>
function saveUn() {
var username = document.getElementById('un').value;
alert(username);
return false;
}
Here is the Code that might help you.
document.getElementById("clickHere").addEventListener("click", function(event){
event.preventDefault()
var username = document.getElementById('un').value;
alert(username);
});
<form >
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" id="clickHere" />
</form>
Try this one if you do not want to submit the form and just want display an alert:
<form onSubmit = "return saveUn();">
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" />
</form>
<script>
function saveUn() {
var username = document.getElementById('un').value;
alert(username);
return false;
}
</script>
You can return boolean value for saveUn(), return false if you do not want to submit
function saveUn() {
var username = document.getElementById('un').value;
alert(username);
return false;
}
<form>
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" onclick="return saveUn();" />
</form>
Using ES6 this should be better:
<form >
Username:
<input type="text" size="12" id="un" /><br />
<input type="submit" id="clickHere" />
</form>
const smBtn = document.querySelector("clickHere");
smBtn.addEventListener("click", (event) => {
event.preventDefault()
let username = document.querySelector('un').value;
alert(username);
});

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/

Validating multiple form fields with JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have already searched the site and while I found similar issues, I couldn't get the answer I needed, so I am asking now. I need to validate a contact form, the PHP validation is very simple but works on a base level, I want to supplement this with browser validation through JS but it is not working, the JS validation does not trigger or is not correctly coded.
I'm working on this page: http://camp-tags.com/?main_page=contact
Thanks in advance for looking for me.
The function is supposed to loop through and make sure that the 4 elements are not empty, and that both variables for phonenumber and email are formatted correctly. If any flag as false, the error is supposed to be pushed to an array and then all errors output in a single alert.
Below is the code. (updated using the tips given here. No validation at all now.)
*update: I found one glaring error I can not believe I missed. I didn't have a closing tag on the , now that is done, the form will not send unless you input the phone correct but is not validating the rest and no Alert is being issued to advise what is wrong?
JS:
function validateForm(event){
var form1 = document.getElementById("form1"),
phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/;
var errors = [];
if (phone){
event.preventDefault();
errors.push("The Phone Number is required.");
return false;
} else if (tomatch.test(phone)){
return true;
} else {
event.preventDefault();
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
return false;
}
if (name === null || name === " "){
event.preventDefault();
errors.push("The Name is required.");
return false;
} else {
return true;
}
if (email === null || email === " "){
event.preventDefault();
errors.push("The email is required.");
return false;
} else if (emailMatch.test(email)){
return true;
} else {
event.preventDefault();
errors.push("The email must be formated as follows: name#domain.com.");
return false;
}
if (address === null || address === " "){
event.preventDefault();
errors.push("The Address is required.");
return false;
} else {
return true;
}
if(errors.length > 0){
for(var i=0;i<errors.length;i++){
alert(errors)
}
return false;
} else {
return true;
}
}
html:
Send Us An Email
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="return validateForm()">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
<script type="text/javascript" src="./assets/validation.js">
I don't know where to start from, but if you need your own validation you should remove required attribute from the inputs because FF for example will check the form instead of your validation function.
Executing event.preventDefault(); what do you think you have in event?
Properlly you should pass it when calling the function on submit and supply an argument in the function definition
onSubmit="validateForm(event);"
and function definition should be:
function validateForm(event) {
...
so you can do event.preventDefault()
...
}
You may have other problems too, but at least you will get the validation function executed and you;ll have event in it
COMPLETE EXAMPLE ADDED:
<script>
function validateForm(event) {
var phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/,
errors = [];
if (!phone){
errors.push("The Phone Number is required.");
} else if (!tomatch.test(phone)){
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
}
if (!name){
errors.push("The Name is required");
}
if (!email){
errors.push("The email is required.");
} else if (!emailMatch.test(email)){
errors.push("The email must be formated as follows: name#domain.com.");
}
if (!address){
errors.push("The Address is required.");
}
if (errors.length) {
event.preventDefault();
alert(errors.join("\n"));
}
}
</script>
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="validateForm(event)">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>

OnSubmit Javascript not overriding submit action

I am trying to build a website with a webform. I am using Godaddy's default webform PHP and I am not sure how to validate the form for required fields.
I want the user to not be able to submit the form prior to validation. I found JavaScript files online submitted by other users that address this problem but I can not seem to get it to work.
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
if (email.indexOf('#') == -1) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Below is the form:
<form onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10">
</textarea><br>
<input type="submit" name="submit" value="submit"/> <span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/> <input type="hidden" name="form_delivery" value="daily"/> <input type="hidden" name="form_format" value="html"/>
I tried submitting without entering anything and it redirects me to the thank you.
form is not defined in the function. There are several ways to handle this. The simplest would be to change return checkForm() to return checkForm(this) and
function checkForm(form) {
In the form, change checkForm() to checkForm(this). Then, in your javascript, change function checkForm() { to function checkForm(form) {
Maybe this will help.
You forgot 2 thing:
first, please add name="form" into
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
second, you misstake close form, please add this code to end of HTML
</form>
Your HTML will look like:
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10"></textarea><br>
<input type="submit" name="submit" value="submit"/>
<span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/>
<input type="hidden" name="form_delivery" value="daily"/>
<input type="hidden" name="form_format" value="html"/>
</form>
1 other thing is in javascript, function to check email address is incorrect, Correct is:
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
// incorrect email address
}
New script will be:
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Goodluck!

Preventing form submission when input field is empty

When no value is provided to the roll input field an alert is produced by the empty() function but this empty value is still passed to retrive.php. So how can I stop this from happening and only pass the value to retrive.php when some input value is provided?
<html>
<head>
<title>STUDENT FORM</title>
<script type="text/javascript">
function empty()
{
var x;
x = document.getElementById("roll-input").value;
if (x == "")
{
alert("Enter a Valid Roll Number");
};
}
</script>
</head>
<body >
<h1 align="center">student details</h1>
<div id="input">
<form action='retrive.php' method='get'>
<fieldset>
<legend>Get Details</legend>
<dl>
<dt><label for="roll-input">Enter Roll Number</label></dt>
<dd><input type="text" name="roll" id="roll-input"><dd>
<input type="submit" value="submit" onClick="empty()" />
</dl>
</fieldset>
</form>
</div>
</body>
</html>
You need to return false to cancel the submit.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Enter a Valid Roll Number");
return false;
};
}
and
<input type="submit" value="submit" onClick="return empty()" />
jsFiddle example
How about using the required attribute?
<input id="Name" name="Name" class="form-control" placeholder="Enter name" type="text" required/>
Only works in html5 though.
The easiest way is to add attribute "required" into the input tag
<input type="text" name="name" required>
<form method="post" name="loginForm" id ="loginForm" action="login.php">
<input type="text" name="uid" id="uid" />
<input type="password" name="pass" id="pass" />
<input type="submit" class="button" value="Log In"/>
<script type="text/javascript">
$('#loginForm').submit(function()
{
if ($.trim($("#uid").val()) === "" || $.trim($("#pass").val()) === "") {
alert('Please enter Username and Password.');
return false;
}
});
</script>
</form>
i use with this I thinking it's maybe can help
$(function () {
$('form').submit(function () {
if ($('input').val() === "") {
alert('Please enter Username and Password.');
return false;
}
});
})
or work with class or ID like this
$('.inputClass')
$('#inputID')
If you want to save code you can simply do:
<input type="text" name="roll" id="roll-input">
<input type="submit" value="submit" onClick="return document.getElementById('roll-input').value !=''"/>
I just say.

Categories