if jQuery statement | empty text boxes - javascript

Ok so i have been literally trying to figure this out for the past hour, its such a simple thing that i never have a problem with. So the input 'username_input' has a jQuery if state that is
if($('#username_input').val() == 0) {
alert('Empty');
} else {
alert('Not empty');
}
After that it moves onto the 'password_input' if statement which is the same thing, but it keeps alerting 'empty'. Why?
<!doctype html>
<html>
<head>
<title> Awflicks </title>
<meta name=viewport content="width=device-width, initial-scale=1">
<link type="text/css" rel="stylesheet" href="index.css">
</head>
<body>
<div id="body_div">
<form action="" method="post">
<div id="username_div"> Username: <input type="text" name="username" id="username_input"> </div>
<div id="password_div"> Password: <input type="password" name="password" id="password_input"> </div>
<div id="retype_password_div"> Retype password: <input type="password" name="retype_password" id="retype_password_input"> </div>
<div type="submit" id="submit_button"> Create Account </div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var $username = $('#username_input').val();
var $password1 = $('#password_input').val();
var $password2 = $('#retype_password_input').val();
function create_account() {
if($username == 0) {
alert('empty');
} else {
alert('not empty')
}
}
$('#submit_button').click(function() {
create_account();
document.forms[0].submit();
})
</script>
</body>
</html>

Because the variable with the value does not get updated when the value changes. It is the value when it is read. You need to read the value when you want it or set the variable onchange.
Also not sure how the value would be zero since there is no value set. Shouldn't you be checking the length? And you are going to want to return a Boolean from your validation function so you know to cancel the form submission.

You can directly use this without defining variables
if(!$('#username_input').val()) // or if(!$('#password_input').val()) for password input
{
alert('empty');
} else {
alert('not empty')
}

You need to refactor as follows to ensure that $username will only store the value once an input has been committed (e.g. once submit has been pressed)
function create_account() {
var $username = $('#username_input').val();
var $password1 = $('#password_input').val();
var $password2 = $('#retype_password_input').val();
if($username == 0) {
alert('empty');
} else {
alert('not empty')
}
}

After you make the changes suggested by the other answers, you are going to have an issue with your form always getting submitted even when the alert shows "Empty". In fact, it will get submitted twice when the alert shows "Not empty". That is because your "submit_button" has type="submit" so it submits the form. You could change to type="button", but my preference is to bind the handler to the form's submit-event, instead of the button's click-event.
$('form').submit(function(event) {
event.preventDefault(); // Stop the form from getting submitted.
var username = $('#username_input').val();
var password1 = $('#password_input').val();
var password2 = $('#retype_password_input').val();
var isValid = true;
if (username == '') {
alert('Empty');
isValid = false;
}
if (isValid) {
this.submit(); // Now submit the form.
}
});

Related

Form validation using javascript and BootstrapDialog

I'm trying to do form validation by using javascript, however, I think there are some issues for the name field.
Whenever I enter any value for name field, it will automatically skip other validation and direct me to index.php.
Another scenario is after I filled in all except name field, it will it will automatically skip other validation and direct me to index.php.
Any help will be appreciated!
<!DOCTYPE html>
<html>
<head>
<!-- https://stackoverflow.com/questions/10585689/change-the-background-color-in-a-twitter-bootstrap-modal
http://nakupanda.github.io/bootstrap3-dialog/
-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link href- "css/trying.css" >
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
<script>
function showError(message) {
BootstrapDialog.show({
title: 'Attention',
message: message,
type: BootstrapDialog.TYPE_DANGER,
buttons: [{
label: 'Ok',
cssClass: 'btn-default',
action: function(dialog) {
dialog.close();
}
}]
});
return false;
}
function validationFunction($msg){
var list = document.createElement('ul');
for(var i = 0; i < $msg.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode($msg[i]));
list.appendChild(item);
}
showError($msg);
return false;
}
function validateForm(form) {
var RE_NAME = /^[A-Z a-z]+$/;
var RE_EMAIL = /^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
var RE_PASSWORD = /^[\S]{6,20}$/
var errors = [];
var name = form.reg_full_name.value;
var email = form.reg_email.value;
var password = form.reg_password.value;
var confirmPass = form.reg_confirmpass.value;
//Name Validation
if (name == "") {
errors.push("Please enter your full name");
}
else if (!RE_NAME.test(x)){
errors.push( "Please enter valid name");
}
//Email Validation
if (!RE_EMAIL.test(email)){
errors.push("Please enter a valid Email");
}
//Password Validation
if (password =="" || confirmPass =="" ){
errors.push( "Password and Comfirmation Password required");
}
else if (!RE_PASSWORD.test(password)){
errors.push("Please a enter a password 6 - 20 characters in length");
}
else if (password!= confirmPass){
errors.push("Your password and confirmation password do not match");
}
//If more than 1 error
if (errors.length > 1) {
validationFunction(errors);
alert(errors);
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action=""
onsubmit="return validateForm(this)" method="post">
Name: <input type="text" name="reg_full_name"><br><br>
Email: <input type="email" name="reg_email"><br><br>
Password: <input type="password" name="reg_password"><br><br>
Confirm Password: <input type="password" name="reg_confirmpass"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The array "errors" doesn't get populated with the correct values.
The correct way to do this would be:
errors.push("Please enter your full name");
Then your errors array gets a new entry "Please enter your full name", which has an index of 0. The array now also has a length of 1. So you would need to adjust the block where you ask if there is more than one error to:
if (errors.length > 1)
Sorry, everyone. I've found the problem.
Is my careless mistake, I've accidentally typed the wrong variable at this line which causes my whole validation
!RE_NAME.test(x)
The problem solved.

checking value for element causing error on onsubmit

I have a form which I am trying to check color of the element before the page submits. I am trying to validate the form using a function called by the from using 'onsubmit='. If I add 'document.getElementById(name).style.backgroundColor' in the code below, when I submit the page it will go directly to the next page without asking if I want to go onto the next page or letting the user know the form has errors. It looks like the form is successfully calling both validate() and check_form() functions, but with the background color check it seems to not complete the validate() function. I've tested it without the 'style.backgroundColor' and it works fine (gives notice to user). What am I doing wrong?
Thanks
Simplified example of the code used:
<!DOCTYPE html>
<html>
<body>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="sample" name="sample" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
var sample = 'sample';
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
if(sample.style.backgroundColor == 'red'){
return 'false';
}
else{
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
test example of check_form function that does work:
function check_form(){
sample = document.getElementById(sample);
return 'false';
}
Edit: The way I have my form set up now is more accurately displayed as:
<!DOCTYPE html>
<html>
<body>
<?php $sample = 'test'; ?>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="<?php echo $sample;?>" name="<?php echo $sample;?>" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
sample = <?php echo json_encode("$sample"); ?>;
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
Where the samples are brought in from another page to dynamically create the form.
sample is a local variable in the dom ready handler which is not accessible in the check form method, but since sample is an id of an element that will be available as a window property(global variable), so you will be getting an error like Uncaught TypeError: Cannot read property 'style' of null.
Instead pass the id as a string literal in the check_form method like
function check_form() {
var sample = document.getElementById('sample');
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
Demo: Fiddle

stopping form submit if the validation fails.

I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.
<script>
function dateCheck()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
document.getElementById('name4').focus();
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);
if(parse_eDate >= parse_sDate)
{
alert("End date should not be greater than one year from start date");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
Just a comment:
If your listener passes a reference to the form, you can access the controls by name or ID:
<form onsubmit="return dateCheck(this)">
then:
function dateCheck(form) {
var start = form.name3.value;
...
}
Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).
function dateCheck(form) {
var start = form.name3.value;
var end = form.name4.value;
var valid = compare(start, end);
if (!valid) form.name4.focus();
return false;
}
I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:
<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">
For the button I have
<input id='submit' type="submit" value="Login" onClick="return pswderr();">
My script is:
<script>
function pswderr() {
var pswd1 = document.getElementById("newuserpswd").value;
var pswd2 = document.getElementById("rptpswd").value;
if (pswd1 !== pswd2) {
document.getElementById("alarm").innerHTML = "Password and password
verification do not match. Retry";
return false;
} else {document.getElementById("alarm").innerHTML = "";
return true;
}
}
</script>
use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!
<script>
function validateForm(){
var validation = false;
var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
if(phonenumber != 11) {
alert("phonenumber is incorrect");
//e.preventDefault();
return false;
}
}
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>
return is not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)
so change your function to this
function dateCheck(e){
var start = document.getElementById('name3').value;
var end = document.getElementById('name4').value;
if(compare(start, end)) {
// no error submit i guess
// return true ?
} else {
// error with date compare
return false;
}
end.focus();
}
In my case i used pattern in input field and also gave maxlength.
What worked with me was, remove Length attribute from input field
you can achieve the same thing using jQuery Form Plugin.
$(document).ready(function() {
$('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } );
});
- I hope this will help you : Just write this code on your Html/jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
- **Don't forget to add this on your html page**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
//option A
$("regF").submit(function(e) { //regF is form id
alert('submit intercepted');
e.preventDefault(e);
});
});
</script>
</html>

javascript form validation object

Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.

Alert box is not working in function while validating username and password using if condition in javascript

function validate() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==null || x==" ") {
alert("Enter username");
}
if(y==null || y==" ") {
alert("Enter password");
}
}
As Twonky commented, we need some additional information. The code that you posted is just a function. I suppose you have two inputs and a button? Do you want the alerts to show when a user clicks the button and the input fields are empty? If you do, you need to add this function as a callback to onclick event.
More about the events:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
https://www.bitdegree.org/learn/onclick-javascript
https://www.w3docs.com/snippets/html/how-to-make-button-onclick-in-html.html
Edit: added corrected code and some links for further reading. The mistake was with looking for white space, instead for an empty string (" ", instead of "")
<!doctype html>
<html>
<head>
<title>Welcome</title>
<script>
function validateForm() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==="" || x===null) {
alert("Enter username");
};
if(y==="" || y===null) {
alert("Enter password");
};
};
</script>
</head>
<body>
<div>
Username:<input type="text" name="un" id="user"/>
Password:<input type="password" name="ps" id="pass"/>
<input type="submit" onclick="validateForm()"/>
</div>
</body>
</html>
Further articles about these topics:
Stackoveflow thread about whitespace and empty strings
An article about the difference between == and ===
P.S.: I had also changed the element from form to div. Since you are using your function in this case as a security so the user wouldn't submit empty data, this is better for now, since form is submitted with your function call and div isn't. You can check the network tab to see, that the page reloads after the function is executed with form element and is not reloaded with the div element.
if(x === undefined || x === null || x.trim() === '') alert('Please enter a username');
if(y === undefined || y === null || y.trim() === '') alert('Please enter a password');

Categories