my html code is below
<script src="js/validate.js"></script>
<label>FIRST NAME:</label>
</td>
<td>
<input type="text" class="firstname" id="firstname" onKeyUp="firstname()" />
</td>
<td>
<label id="fn"></label>
and my js code is below
function firstname()
{
var nname=document.getElementById("firstname").value;
var l=nname.length > 3 ;
if( !l)
{
producePrompt("firstname should not be less than 4 characters","fn","red");
return false;
}
else
if(!nname.match(/^[a-zA-Z\s]*$/))
{
producePrompt("incorrect name","fn","red");
return false;
}
else
{
producePrompt("correct","fn","green");
return true;
}
}
function producePrompt(message,promptlocation,color)
{
document.getElementById(promptlocation).innerHTML= message;
document.getElementById(promptlocation).style.color= color;
}
but my code is not showing the messages or does not validate it properly
the js is under a file named validate.js and html is in index.html
i tried both types (,) to include the js file but no validation is taking place
try this , works fine for me (validation works) :
js :
function checkinput()
{
var nname=document.getElementById("firstname").value;
var l=nname.length > 3 ;
if(!l)
{
console.log("firstname should not be less than 4 characters","fn","red");
return false;
}
else
if(!nname.match(/^[a-zA-Z\s]*$/))
{
console.log("incorrect name","fn","red");
return false;
}
else
{
console.log("correct","fn","green");
return true;
}
}
html:
<form>
<label>FIRST NAME:</label> <input type="text" class="firstname" id="firstname" onblur="checkinput()" />
</form>
<body>
// all your html contents
// load the scripts here
<script src="js/validate.js"></script>
</body>
OR
<body>
// all your html contents
<script>
// javascript contents
</script>
</body>
Related
I am very new to js and html, could someone help me understand as to why my page is getting redirected to the next page even if the validation fails and my "validate()" function returns only FALSE!
I have created a form that takes name, age, email, state etc as input and it should ideally validate them and then proceed towards the next page.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name_length<10)
{
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at))
continue;
else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate();">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
Could somebody please help me with why my code redirects directly to handle.html without checking for validations?
You're trying to get the length of name as follow: name_length this is a typo, however, you have another error: a continue keyword
if((/(\w|\d|.)/).test(before_at))
continue;
^
else
Changed to:
if((/(\w|\d|.)/).test(before_at)) {
//continue; You need to modify this part.
} else {
alert("Please enter a valid email address");
return false;
}
You need to understand that continue keyword must be placed within a loop, i.e: for-loop.
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(e){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name.length<10)
{
alert('Please enter name correctly!');
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at)) {
//continue;
} else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate(event);">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
If you want to start learning web development with html and javascript, i suggest learn shortest way to do it. For javascript validation check this jquery validation
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" name="userForm" id="userForm" method="post">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
<script type="text/javascript">
$('#userForm').validate({
rules: {
name :{
required : true
},
email: {
required : true,
email : true,
},
age: {
required: true,
minlength:18, // Can define minimum age
maxlength:60 // max page
}
},
submitHandler: function(form) {
alert("All Well") ;
$("#userForm").submit(); // form tag id to sumit the form
return false ;
}
});
</script>
</body>
</html>
With jquery validation you can lots too much work with very short hand code.
Hope this will help, All the best.
I'm a complete noob at this stuff.
But my goal here is to accept a certain username and validate it with a certain password.
I've searched and searched all night to no avail so here I am looking for an answer.
My code in html:
<form action="" method="POST" id="loginForm">
<label for="userName" accesskey="F"><br>Username:</label>
<input type="username" name="userName" id="userName">
<label for="password"><br>Password: </label>
<input type="password" name="password" id="password">
<button>Submit</button>
</form>
My code in a seperate javascript file (which is being called by the html file):
function validate(id) {
var guest1User = /guest1/;
var guest2User= /[guest1]/;
var guest1Pass= /[guest2]/;
var guest2Pass= /[guest1]/
var userCheck= document.getElemetnById(userName);
var passCheck= document.getElementById(password);
if (guest1User.test(userCheck.value)) {
if (guest1Pass.test(passCheck.value)) {
return true;
} else {
return false;
}
}
if (guest2User.test(guestCheck.value)) {
if (guest2Pass.test(passCheck.value)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
validate();
Try the following approach:
As per your comment you were wondering how would the js file know that its function has been called.... therefore you need to include the js file in the html file in the following way:
<script type="text/javascript" src="somefile.js"></script>
make sure the path to the somefile.js is correct for example if your file system is like that:
/root/js/
/root/html/
<script type="text/javascript" src="../js/somefile.js"></script>
and your html file is inside the html folder then you refer to the js file as:
function validate(id) {
var guest1User = /guest1/g;
var guest2User= /[guest1]/g;
var guest1Pass= /[guest2]/g;
var guest2Pass= /[guest1]/g;
var userCheck= document.getElementById('userName');
var passCheck=document.getElementById('password');
if (guest1User.test(userCheck.value)) {
console.log("true");
if (guest1Pass.test(passCheck.value)) {
console.log("true");
return true;
} else {
console.log("false");
return false;
}
}
else
{
console.log("false");
return false;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--
<script type="text/javascript" src="../js/somefile.js"></script>
-->
</head>
<body>
<form action="#" method="POST" id="loginForm">
<label for="userName" accesskey="F"><br>Username:</label>
<input type="username" name="userName" id="userName">
<label for="password"><br>Password: </label>
<input type="password" name="password" id="password">
<input type=submit onclick="return validate();" value="submit"/>
</form>
</body>
</html>
I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">
Essentially, I am trying to have my form clear all input fields on submit if the default values are still present. Then if there are default values still present, then the submit process is stopped. The form clears the fields on submit, but wont stop the submit button from executing like its suppose to. Please help me out on this. I wrote this myself, and still trying to figure out why it isn't working.
The jQuery Script Below:
<script type="text/javascript" >
$(document).ready(function(){
$(".forms").each(function(){
var DefaultValue = $(this).value;
$("#Form_1").submit(function(){
if ( CheckInput() == "empty" ){
return false;
}
});
function CheckInput(){
var x = '';
$(".forms").each(function(){
if ($(this).value == DefaultValue){
this.value = '';
var y = "empty";
return y;
}
x = y;
return x;
});
}
});
});
</script>
The HTML code below:
<form id="Form_1">
<table>
<tr>
<td>
<table cellpadding="2" cellspacing="3" width="500px">
<tr>
<td>
<div class="InputContainer">
<input name="FirstName" value="First Name" class="forms" type="text"required="true" ></input>
<div class="InfoBlurp">First Name<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="BirthDate" value="Birth Date(MM/DD/YYYY)" class="forms" type="text" required="true" ></input>
<div class="InfoBlurp">Birth Date(MM/DD/YYYY)<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="Email" value="Email#sample.com" validType="email" class="forms" type="text" required="true"/></input>
<div class="InfoBlurp">Email#sample.com<div class="InfoTip"></div></div></div>
</td>
</tr>
</table>
<input id="Button_1" class="topopup" type="submit" value="" style="background-color: #FFFFFF; border:none; cursor:pointer;">
</form>
Your checkInput method is not returning anything, you are returning values from the each callback function not from the CheckInput method.
$(document).ready(function () {
$(".forms").each(function () {
var DefaultValue = $(this).value;
$("#Form_1").submit(function () {
if (CheckInput() == "empty") {
return false;
}
});
function CheckInput() {
var x = '';
$(".forms").each(function () {
if ($(this).value == DefaultValue) {
this.value = '';
x = "empty";
//return false to stop further iteration of the loop
return false;
}
});
return x;
}
});
});
I have written the following code in html and the javascript file is also embedded below
<!DOCTYPE html>
<meta charset="utf-8">
<HTML>
<head>
<link rel="stylesheet" href="admin.css"/>
<script type="text/javascript" src="common.js"></script>
</head>
<BODY>
<div class="adminnav" id="adminnav">
<ul>
<li>Insert
<ul>
<li>Insert Course</li>
<li>Insert Student</li>
<li>Insert Teacher</li>
<li>Insert Subject</li>
</ul>
</li>
</ul>
</div>
<div class="addcourse" >
<form name="course" onSubmit='return validcourse()' method="POST">
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:<input type="text" name="cd"/>
<br>
Course Id:<input name="cid" type="text" /><br>
<input type="submit" value="submit" name="submit"><input type="reset" name="coursereset">
</form>
</div>
</BODY>
</HTML>
common.js
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
}
}
}
}
}
function course_name_valid(course_name)
{
var letters=/^[A-Za-z]+$/;
if(course_name.value.match(letters))
{
return true;
}
else
{
alert("Course name must have alphabets only");
course_name.focus();
return false;
}
}
function course_duration_valid(course_duration)
{
var letters=/^[1-9]+$/;
if(cd.value.match(letters))
{
return true;
}
else
{
alert("Course Duration can have numbers only");
course_duration.focus();
retun false;
}
}
function course_id_valid(course_id)
{
var letters=/^[0-9a-zA-z]+$/;
if(course_id.value.match(letters))
{
return true;
}
else
{
alert('Course ID must have character and numeric values only');
course_id.focus();
return false;
}
}
My problem is that nothing is happening no error messages are given.
Error messages are given only for course name but not for course duration and course id?
Here is a link to jsfiddle http://jsfiddle.net/amolkarale/aTfq6/1/
You are not returning anything from validcourse. Add a return true; and return false; in there, to either let the submission continue or stop the submission from happening:
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
return true;
}
}
}
}
return false;
}
Looks like you have a syntax error in your third functioncourse_duration_valid(course_duration)
retrun false;
should be:
return false;
Okay, so I got your stuff to work. Here are the changes needed:
First, object references need to be cleaner in your DOM
var course_name=document.getElementById("cname");
var course_duration=document.getElementById("cd");
var course_id=document.getElementById("cid");
As you can see, the elements need to have their individual ids.
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:
<input type="text" name="cd" id="cd"/><br>
Course Id:
<input name="cid" type="text" id="cid" /><br>
Finally, the retrun needed to be corrected, as already pointed out by #Steve