Javascript validations - javascript

form validation
<html>
<head>
<link rel="stylesheet" type ="text/css" href ="home.css">
<script src ="contact.js"></script>
<title>Barber</title>
</head>
<body>
<script src ="contact.js"></script>
<ul>
<li><a class="active" href="barber.html">Home</a></li>
<li> Gallery</li>
<li>Appointment (php) </li>
<li>About</li>
<li> Contact Us (javascript)</li>
<li>Log In(php, java, sql) </li>
</ul>
<li2>
<h2>Contact Us:</h2>
</li2>
<div>
<form name= "form" method "post" onsubmit="return validateForm()" >
Name: <input type="text" id= "name" name= "name"/>
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" placeholder="JohnDoe#example.com" />
<br>
<label for="website">Phone Number:</label>
<input type="text" name="Phone" id="Phone" placeholder="###-###-####" />
<br>
<label for="message">Message:</label>
<textarea name="message" id='message' cols="40" rows="6">
</textarea>
<br>
<input type ="submit" name="submit" value = "submit" >
</form>
</div>
</body>
</html>
external javascript
<script type = "text/javascript">
function validateForm(){
if (document.form.name.value=="") {
alert("Empty");
}
return;
}
</script>
So I'm trying to validate all of my fields using JavaScript, I am unable to get it to work at all and I've been doing this all day. I had started out with more script than this but it didn't work. So I got rid of it. I think if I can figure out how to validate one field, I should be able to figure out the rest. Can anyone help me out with this?
Also where to I put the external link for my script?

In you contact.js, just include the js functionality, no need to have the <script> tag
Your contact.js should look something like:
contact.js
function validateForm(){
if (document.form.name.value=="") {
alert("Empty");
}
return;
}

You should try with this;
Give one common class to all like class="required".
And then write your javascript like below,
<script type = "text/javascript">
function validateForm(){
if ($(".required").val() == "")
{
alert("Empty");
return false;
}
return;
}
</script>

You should use
return false;
like this.
if (document.form.name.value=="")
{
alert("Empty");
return false;
}

function validateForm() {
var x = document.forms["form"]["value"].value;
if (x == null || x == "") {
alert("Empty");
return false;
}
}

Try this for single field check.
var dataValue = document.getElementById("name").value;
if (dataValue == "") {
alert("Empty");
return false;
}

Related

Html Form Unable to Validate Inputs using JavaScript

I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

How to solve validation using multiple buttons in a form

I have a form, with a number of textboxes which a user can fill in. At the bottom of the form I have two buttons. One for canceling and one for submitting. Like the example below
<form action='bla.php' method='post'>
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<input type='submit' name='submit'>
<input type='submit' name='cancel'>
</form>
And I have a js function that checks the fields for their data which I used to use for both buttons. I therefor refer to the js function in the form as below:
<form action='bla.php' method='post' name='form' onSubmit='return CheckFields()'>
The js function looks like this:
function CheckFields() {
var formname = "form";
var x = document.forms[formname]["someTextField1"].value;
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
Now I want this js function to only run when using the submit and not the cancel button. When I try to move the call to the function to the submit button as below it doesn't work:
<input type='submit' name='submit' onClick='return CheckFields()'>
<input type='submit' name='cancel'>
Why? What is the smartest way of solving this? Should I leave the call to CheckFields() in the form and check within the script what button was clicked or should I remake the function to somewhat work with a button instead? Anyone have an idea or an example?
replace <input type='submit' name='cancel'> by <input type='button' name='cancel'>.Your Version actually has two submit-buttons, both of which will submit the form.
Watch this sample http://jsfiddle.net/355vw560/
<form action='bla.php' method='post' name="form">
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<br/>
<input type='submit' name='submit' onclick="return window.CheckFields()">
<input type='submit' name='cancel' value="cancel" onclick="return false;">
anyway it's always better to use jquery or event listeners instead of managing events directly in the dom.
The function didnt worked because its scope was the element, if u specify window as context your function works.
First at all, it's not needed have submit button on a form if you want to use javascript to check all the fields before submitting.
I think the smartest way of doing it will be as follow:
Your form (without action, submit button, and method. Only identifing each component with id's):
<form id="formId">
<input type='text' id="text1">
<input type='text' id="text2">
<input type='text' id="text3">
<input type='button' id="accept">
<input type='button' id="cancel">
</form>
Your javascript (you have to have jQuery added):
jQuery("#formId").on("click", "#accept", function(){ //listen the accept button click
if(CheckFields()){ //here you check the fields and if they are correct
//then get all the input values and do the ajax call sending the data
var text1 = jQuery("#text1").val();
var text2 = jQuery("#text2").val();
var text3 = jQuery("#text3").val();
jQuery.ajax({
url: "bla.php",
method: "POST",
data: {
"someTextField1":text1, //In your example "someTextField1" is the name that the bla.php file is waiting for, so if you use the same here, it's not needed to change anything in your backend.
"someTextField2":text2,
"someTextField3":text3
},
success: function(){
//here you can do whatever you want when the call is success. For example, redirect to other page, clean the form, show an alert, etc.
}
});
}
});
jQuery("#formId").on("click", "#cancel", function(){ //here listen the click on the cancel button
//here you can clean the form, etc
});
function CheckFields() { //here I did a little change for validating, using jQuery.
var x = jQuery("#text1").val();
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
I hope it helps you!
I handle it with this way , Hope it will help.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form method="post" action="/">
<div class="container" style="background: #efefef; padding: 20px;">
<label>Encrypt and decrypt text with AES algorithm</label>
<textarea name="inputText" id = "inputText" rows="3" cols="100" placeholder="Type text to Encrypt..." maxlength="16" ></textarea>
<br>
<br>
<textarea name="inputKey" id = "inputKey" rows="1" cols="100" placeholder="Type key to Encrypt\Decrypt text with..." maxlength="16"></textarea>
<br>
<br>
<label>SBox :</label>
<div>
<div class="s-box-radios">
<ul class="sbox">
<li>
<label>SBox 1
<input id="sbox1" name="sboxOption" type="radio" value="option1" required/>
</label>
</li>
<li>
<label>SBox 2
<input id="sbox2" name="sboxOption" type="radio" value="option2" />
</label>
</li>
<li>
<label>SBox 3
<input id="sbox3" name="sboxOption" type="radio" value="option3" />
</label>
</li>
<li>
<label>SBox 4
<input id="sbox4" name="sboxOption" type="radio" value="option4" />
</label>
</li>
</ul>
</div>
<div class="s-box-display">
<textarea rows="5" cols="10"></textarea>
</div>
</div>
<div class="clear"></div>
<br>
<label>Result of Decryption in plain text</label>
<textarea name="inputCipher" rows="3" cols="100" placeholder="Encrypted Texts..." name="decrpyted"></textarea>
<br>
<input type="submit" value="Encrypt" name="Encrypt" id ="encrypt" onclick="valEncrypt()" />
<input type="submit" value="Decrypt" name="Decrypt" id ="decrypt" onclick="valDncrypt()" />
</div>
</form>
<script>
function valEncrypt()
{
var inputText = document.getElementById('inputText');
var inputkey = document.getElementById('inputKey');
if (inputText.value.length <16)
{
doAlert(inputText);
return false;
}
else
{
removeAlert(inputText);
}
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
else
{
removeAlert(inputkey);
}
}
function valDncrypt()
{
var inputkey = document.getElementById('inputKey');
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
alert('!Success');
}
function doAlert(element){
element.style.border = "1px solid #FF0000";
}
function removeAlert(element){
element.style.border = "1px solid #000000";
}
</script>
</body>
</html>

how to show an error message beside field in html using javascript please help me [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 wrote a program using javascript for showing error message beside field instead of alerting but it is not working please help me to work the program
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript">
function check()
{
if(document.getElementById('firstname').value==NULL || myform.firstname.value.length==0)
{
document.getElementById('errorname').value="this is an invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
<p>name</p>
<input type="text" name="firstname" onblur="check()"/>
<span id="errorname"></span>
<br/><input type="button" value="submit" />
</form>
</body>
</html>
you have not given the id to you textbox also pass the value of textbox into the function
like this
<input type="text" name="firstname" id="firstname" onblur="check(this.value)"/>
And JS Function
function check(value)
{
if(value.trim()=="")
{
document.getElementById('errorname').innerHTML="this is an invalid name";
}
}
SEE FIDDLE DEMO
You are not provided ID for your input field. Add an ID and access your input field.
function check(){
if(document.getElementById('firstname').value==""){
document.getElementById('errorname').innerHTML ="this is an invalid name";
}
}
And change your html field like this.
<input type="text" name="firstname" id="firstname" onblur="check()"/>
HTML:
<form id="form">
<p>name</p>
<input type="text" id="firstname" name="firstname" /> <span id="errorname"></span>
<br/>
<input type="submit" value="Submit" />
</form>
JavaScript:
var form = document.getElementById('form'),
firstName = document.getElementById('firstname'),
errorMessage = document.getElementById('errorname');
function check(event) {
event.preventDefault();
if (firstName.value === '' || !firstName.value.length) {
console.log('here')
errorMessage.innerText = 'This is an invalid name';
} else {
errorMessage.innerText = '';
}
}
form.addEventListener('submit', check);
JSFiddle example:
http://jsfiddle.net/2etd93jL/2/
You have used document.getElementById('firstname') but your input input type="text" name="firstname" doesn't have an id, only a name. try adding id="firstname" to the input box.
Multiple errors in your code listing down below:
Use of NULL: it is null and not NULL.
No id assigned as firstname and checking for that in the if loop
to give value to span need to use innerHTML
So your HTML code:
<form name="myform">
<p>name</p><input id="firstname" type="text" name="firstname" onblur="check()"/><span id="errorname"> </span>
<br/><input type="button" value="submit" />
</form>
JS Code:
function check()
{
if(document.getElementById('firstname').value==null || myform.firstname.value.length==0)
{
document.getElementById('errorname').innerHTML="this is an invalid name";
}
}
Working Fiddle
This is almost your code, few changes did to meet the requirement.
Checkout the fiddle
function check(){
if(document.getElementById('firstname').value=='' || !document.getElementById('firstname').value.length){
document.getElementById('errorname').innerHTML="this is an invalid name";
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<script type="text/javascript">
function check() {
if (document.myform.firstname.value === null || myform.firstname.value.length == 0) {
document.getElementById('errorname').innerHTML = "this is an invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
<p>name</p>
<input type="text" name="firstname" onblur="check()" /><span id="errorname"> </span>
<br />
<input type="button" value="submit" />
</form>
</body>
</html>

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.

Unable to get Alert Pop-Up on IE...Works fine in Firefox,Chrome etc.?

I am trying to get pop-up block when there is no text/blank space. It is working fine in Firefox, Chrome &Safari.
Please check below code in my JavaScript file-:
function submitQuestion(URL,docId,errorMessage)
{
var question = $('textField').value;
if(!question.blank())
{
var submitForm = $("question-form");
submitForm.action = URL+"docId="+docId+"&question="+encodeURIComponent(question);
//alert(submitForm.action);
submitForm.submit();
}
else
{
alert(errorMessage);
return false;
}
}
Above function works fine in Firefox,Safari &Chrome as when there is nothing in textbox (i.e. empty/blank) then it goes to else &prompt errorMessage as a pop-up but in IE, it doesn't go to else &errorMessage pop-up never come.
Please check below code for my forntend form-:
<form method="POST" id="question-form" onsubmit="return submitQuestion('https://localhost/question-post!input.jspa?','ABC12','Enter your question!');">
<span class="fieldwrap">
<input type="text" placeholder="Ask customers about this document" value="" maxlength="255" autocomplete="off" class="questionInputField" id="textField">
</span>
<div class="clear"></div>
<div id="question-submit" class="widget-div clearfix">
<input type="submit" value="Submit question to the portal" class="questionSubmitFormButton">
</div>
</div>
</form>
What happened here in IE is it will take placeholder as a value for text field when we didn't provide any i.e. When we keep text field empty or blank then it will take placeholder as a text field value &instead of giving pop-up alert, it goes to if loop which should not be a case.
To access the value of the textField using jQuery, you should use val() instead of value.
var question = $('textField').val();
if (question != '') {
//
}
else {
//
}
Below is a working example:
<!DOCTYPE html>
<head>
<title>EXAMPLE</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function submitQuestion(URL, docId, errorMessage) {
var question = $('#textField').val();
if (question.trim() != "") {
var submitForm = $("#question-form");
submitForm.attr("action", URL + "docId=" + docId + "&question=" + encodeURIComponent(question));
return true;
}
else {
alert(errorMessage);
return false;
}
}
</script>
</head>
<body>
<form method="POST" id="question-form" onsubmit="return submitQuestion('https://localhost/question-post!input.jspa?','ABC12','Enter your question!');">
<span class="fieldwrap">
<input type="text" placeholder="Ask customers about this document" value="" maxlength="255" autocomplete="off" class="questionInputField" id="textField">
</span>
<div class="clear"></div>
<div id="question-submit" class="widget-div clearfix">
<input type="submit" value="Submit question to the portal" class="questionSubmitFormButton">
</div>
</form>
</body>

Categories