i'm trying to validate a form using a simple javascript script however it is not working, can anyone tell me what is wrong with my code? (sorry for my vague question)
JS code:
<script type="text/javascript">
function validation()
{
var fName=document.forms["teacherReg"]["firstname"].value;
var lName=document.forms["teacherReg"]["lastname"].value;
var uName=document.forms["teacherReg"]["username"].value;
var pWord=document.forms["teacherReg"]["password"].value;
var cPWord=document.forms["teacherReg"]["confirmpassword"].value;
if (fName="" || lName="" || uName="" || pWord="")
{
alert("Not a valid entry");
return false;
}
}
</script>
html form:
<form name="teacherReg" action="" method="POST" onsubmit="return validation();">
1. First name:
2. Last name:<br/><input type="text" name="firstname" id="firstname" />
<input type="text" name="lastname" id="lastname" /><br/><br/>
3. Desired Username:
<br/><input type="text" name="username" id="username" /><br/><br/>
4. Desired Password:
5. Confirm Password:<br/><input type="password" name="password" id="password" />
<input type="password" name="confirmpassword" id="confirmpassword" /> <br/><br/>
<center><input type="submit" value="Register" name="submitbutton" class="button" /></center>
</form>
I expect it to return false if any of the fields "fName, lName, uName, pWord" are blank, however it is always returning true
The problem is that you confused = (assignment operator) operator with == (comparison operator):
if (fName = "" || lName = "" || uName = "" || pWord = "") {
It should be
if (fName == "" || lName == "" || uName == "" || pWord == "") {
Fixed demo: http://jsfiddle.net/49xDH/
This is the problem:
if (fName=="" || lName=="" || uName=="" || pWord=="")
= is assignment operator , where == is comparison operator. use == for comparing values.
Use the comparison operator == instead of the assignment operator =.
Please try to use the ID instead of the form object.
function validation(){
var username = document.getElementById('username').value;
// etc.
}
Related
I have a webform in which a user has to fill in details. I am using Javascript and html in order to do multiple input validation with regular expressions. I have part of the javascript + html code below. The variables a-g are regexes of each input field required.
I created an empty Array called Err_arr to stored the errors that has met the conditions (e.g. if the user does not input anything / if the user does not fulfil the required format of input) The error message will be pushed into the array. The last if statement will be used to check whether the array is not empty, hence it will print out all the error messages on multiple lines depending on what the conditions are.
function validateForm() {
var cname = document.getElementById("cname").value;
var odate = document.getElementById("odate").value;
var cno = document.getElementById("cno").value;
var ccn = document.getElementById("ccn").value;
var expm = document.getElementById("expm").value;
var expy = document.getElementById("expy").value;
var cvv = document.getElementById("cvv").value;
var Err_Arr = [];
var a = /^(\w\w+)\s(\w+)$/;
var b = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var c = /[0-9]{8}/;
var d = /[0-9]{16}/;
var e = /0[0-1]1[0-9]){2}/;
var f = /[0-9]{4}/;
var g = /[0-9]{3}/;
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (odate == null || odate == "") {
Err_Arr.push("Please Enter Info - Order Date");
}
if (cno == null || cno == "") {
Err_Arr.push("Please Enter Info - Contact No");
}
if (ccn == null || ccn == "") {
Err_Arr.push("Please Enter Info - Credit Card Number");
}
if (expm == null || expm == "") {
Err_Arr.push("Please Enter Info - Expiry Month");
}
if (expy == null || expy == "") {
Err_Arr.push("Please Enter Info - Expiry Year");
}
if (cvv == null || cvv == "") {
Err_Arr.push("Please Enter Info - CVV No");
}
if (cname.test(a) == false) {
Err_Arr.push("Enter correct input");
}
if (odate.test(b) == false) {
Err_Arr.push("Enter correct input");
}
if (cno.test(c) == false) {
Err_Arr.push("Enter correct input");
}
if (ccn.test(d) == false) {
Err_Arr.push("Enter correct input");
}
if (expm.test(e) == false) {
Err_Arr.push("Enter correct input");
}
if (expy.test(f) == false) {
Err_Arr.push("Enter correct input");
}
if (cvv.test(g) == false) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \> Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \> Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \> Credit card number: (e.g. 123456789) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \> Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \> Expiry date - year part (yyyy): <input id="expy"
type="text" name="expy" autocomplete="off"> <br \> CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
I expect the whole web form to give me a whole list of alerts in the conditions that I did not satisfy for the if statements. Instead, my code is not running at all.
The intent of your code is correct. Reason why alerts doesn't show:
A syntax error in var e. notice the missing pair of the parenthesis. should be /0[0-1]1([0-9]){2}/;
.test() is used incorrectly. please refer to w3schools tutorial how to use test. Basically, test() is a method in the Regexp object in javascript. So it should be like regexObject.test(yourString)
Fixing all that most likely will make your code run without issues.
function validateForm() {
var cname = document.getElementById("cname").value;
var Err_Arr = [];
var a = new RegExp(/^(\w\w+)\s(\w+)$/);
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (!a.test(cname)) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name:<input id="cname" type="text" name="cname" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
You have some mistakes:
an invalid regex for e as it has unbalanced parentheses
Strings don't have a test method; regexes do
The suggestion for the credit card number in your HTML would not pass the corresponding regex (that requires 16 digits)
There are also some shorter ways to do things:
if (cname == null || cname == "")
can be just:
if (!cname)
More importantly, you have a lot of code repetition. You could avoid that by doing things in a loop:
function validateForm() {
var validations = [
{ input: "cname", regex: /^(\w\w+)\s(\w+)$/, name: "Customer name" },
{ input: "odate", regex: /^(0?[1-9]|[12]\d|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/, name: "Order date" },
{ input: "cno", regex: /^\d{8}$/, name: "Contact No" },
{ input: "ccn", regex: /^\d{16}$/, name: "Credit Card Number" },
{ input: "expm", regex: /^0?[1-9]|1[012]$/, name: "Expiry Month" }, // Correct regex
{ input: "expy", regex: /^\d{4}$/, name: "Expiry Year" },
{ input: "cvv", regex: /^\d{3}$/, name: "CVV No" }
];
var errors = validations.map(({input, regex, name}) => {
var value = document.getElementById(input).value;
if (!value) return "Please Enter Info - " + name;
if (!regex.test(value)) return "Enter correct input - " + name;
}).filter(Boolean);
if (errors.length) {
alert(errors.join("\n"));
return false;
}
return true;
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \>
Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \>
Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \>
Credit card number: (e.g. 1234567890123456) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \>
Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \>
Expiry date - year part (yyyy): <input id="expy" type="text" name="expy" autocomplete="off"> <br \>
CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
I want to use javascript to validate my form's input before sending the data to the php file. I tried using onSubmit, but for some reason the javascript function is getting skipped over and the data is going straight to the php file. I'm not sure what's wrong with my code- I'd initially put the javascript in another file, then I included it in the page itself with a <script> tag, it's still not working. Here's my code-
The form-
<form action="includes/register.inc.php" name="registration_form" method="post" onSubmit="return regform(this.form,
this.form.first-name, this.form.last-name, this.form.signup-username, this.form.signup-email,
this.form.signup-password, this.form.confirm-password);">
<input id="first-name" name="first-name" type="text" placeholder="First Name"/>
<input id="last-name" name="last-name" type="text" placeholder="Last Name"/>
<input id="signup-username" name="signup-username" type="text" placeholder="Username"/>
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail"/>
<input id="signup-password" name="signup-password" type="password" placeholder="Password"/>
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password"/>
<input type="submit" value="CREATE ACCOUNT"/>
</form>
Javascript-
function regform(form, fname, lname, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
fname.value == '' ||
lname.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if(!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if(!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
it's not this.form, since this already refers to the form. also you need to use brackets for any properties that contain a hyphen as JS will think it's a minus sign. this['last-name']
Try this. Instead of pass a bunch of params to the function, I'm passing the form itself, then pulling out values from there.
function regform(form) {
// Check each field has a value
if (form['signup-username'].value == '' ||
form['signup-email'].value == '' ||
form['signup-password'].value == '' ||
form['first-name'].value == '' ||
form['last-name'].value == '' ||
form['confirm-password'].value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if (!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if (!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if (!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
<form action="" name="registration_form" method="post" onSubmit="return regform(this);">
<input id="first-name" name="first-name" type="text" placeholder="First Name" />
<input id="last-name" name="last-name" type="text" placeholder="Last Name" />
<input id="signup-username" name="signup-username" type="text" placeholder="Username" />
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail" />
<input id="signup-password" name="signup-password" type="password" placeholder="Password" />
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password" />
<input type="submit" value="CREATE ACCOUNT" />
</form>
Here is html code for text field what to check for empty/null values
function myFormValidation() {
alert("HI");
var name = document.getElementById("name").value;
alert(name);
if (name == null || name == " ") {
document.getElementById("inp1").innerHTML = "Enter your name please";
} else {
document.myForm.submit();
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" name="inp1" />
<input type="button" value="Register" onclick=" myFormValidation()" />
I want to validate using innerHtml, but my js is not getting called.
I guess removing the space between " " may work
your code
if(name==null || name ==" " ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
change to
if(name==null || name =="" ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
You might like to validate the input edit through the help of regular expressions
if ( name == null || /\s*/g.test(name) )
{
document.getElementById("inp1").innerHTML = "Enter your name please";
}
The expression \s* covers both the empty string as well as the input consists of multiple blank spaces, such as " " for example
I'm not really familiar with JavaScript/jQuery but I think this is what you're looking for. I've changed your input for the message to label because your type is hidden which also means that users will not be able to see the message at all.
Also, you didn't include the id attribute for your inp1 so it's impossible to use getElementbyId().
function myFormValidation() {
if (document.getElementById("name").value == "") {
document.getElementById("inp1").innerHTML = "Enter your name please";
}
else {
var name = document.getElementById("name").value;
alert("HI");
alert(name);
document.myForm.submit();
}
}
Name:
<input type="text" name="name" id="name" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<label id="inp1"></label>
Here is example:
function myFormValidation() {
var user = document.getElementById("name").value;
if (user === "") {
document.getElementById("body").innerHTML = "Enter your name please";
} else {
document.getElementById("body").innerHTML = user + " " + "How are you..!";
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<div id="body"></div>
i have the code as shown below,
this is the html part.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="regi.js" ></script>
</head>
<body class="regbody">
<form align="center" method="POST" action="submit()" name="regform">
<div id="regpgdiv">
<span class="indextext">Fill in the details below to get registered! </span><br><br><br><br><br><br>
<input type="text" name="regfname" id="ip" value="Enter name" onfocus="if(this.value == 'Enter name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter name'; }" /> <br><br>
<input type="text" name="reguname" id="ip" value="Enter Desired Username" onfocus="if(this.value == 'Enter Desired Username') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter Desired Username'; }" /> <br><br>
<input type="password" name="regpwd" id="ip" value="Select Password" onfocus="if(this.value == 'Select Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Select Password'; }" /> <br><br>
<input type="password" name="cregpwd" id="ip" value="Re-enter Password" onfocus="if(this.value == 'Re-enter Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Re-enter Password'; }" /> <br><br>
<input type="submit" value="Register" id="credsub" >
</div>
</form>
</body>
and the js code is below for the Submit function
function Submit(){
var fname = document.form.regfname.value,
uname= document.form.reguname.value,
fpassword = document.form.regpwd.value,
cfpassword= document.form.cregpwd.value;
if( uname == "" || uname == "Enter Desired Username")
{
document.form.reguname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the username";
return false;
}
if( fname == "" || fname == "Enter name")
{
document.form.regfname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the first name";
return false;
}
if(fpassword == "" || fpassword == "Select password" )
{
document.form.regpwd.focus();
document.getElementById("errorBox").innerHTML = "enter the password";
return false;
}
if (!(cfpassword.equals(fpassword)) )
{
document.form.cregpwd.focus();
document.getElementById("errorBox").innerHTML = "doesnt match";
return false;
}
if(fname != '' && fpassword != '' && cfpassword != '' && uname!= ''){
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
}
when i click the regiter button, it says this webpage has npt been found.
i am new to javascript and need help. thanks in advance.
Yet Another Update - I realised there are errors in your Javascript code for referencing DOM objects (as well as a typo in your validation logic), below are the working modified code. In short, I have added id's to the form elements for referencing, and in your validation logic, you should be check Select Password instead of Select password.
The HTML form
<form align="center" method="POST" action="TARGET-PAGE-TO-HANDLE-DATA" name="regform" id="regform" onsubmit="return Submit()">
<div id="regpgdiv">
<span class="indextext">Fill in the details below to get registered! </span><br><br><br><br><br><br>
<input type="text" name="regfname" id="fname" value="Enter name" onfocus="if(this.value == 'Enter name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter name'; }" /> <br><br>
<input type="text" name="reguname" id="uname" value="Enter Desired Username" onfocus="if(this.value == 'Enter Desired Username') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter Desired Username'; }" /> <br><br>
<input type="password" name="regpwd" id="regpwd" value="Select Password" onfocus="if(this.value == 'Select Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Select Password'; }" /> <br><br>
<input type="password" name="cregpwd" id="cregpwd" value="Re-enter Password" onfocus="if(this.value == 'Re-enter Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Re-enter Password'; }" /> <br><br>
<input type="submit" value="Register" id="credsub" >
</div>
</form>
JS
function Submit() {
var fname = document.getElementById("fname");
var uname= document.getElementById("uname");
var fpassword = document.getElementById("regpwd");
var cfpassword= document.getElementById("cregpwd");
if (uname.value == "" || uname.value == "Enter Desired Username") {
uname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the username";
return false;
}
if (fname.value == "" || fname.value == "Enter name") {
fname.focus();
document.getElementById("errorBox").innerHTML = "enter the first name";
return false;
}
if (fpassword.value == "" || fpassword.value == "Select Password" ) {
fpassword.focus();
document.getElementById("errorBox").innerHTML = "enter the password";
return false;
}
if (cfpassword.value != fpassword.value) {
cfpassword.focus();
document.getElementById("errorBox").innerHTML = "doesnt match";
return false;
}
if (fname.value != '' && fpassword.value != '' && cfpassword.value != '' && uname.value != '') {
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
return true;
}
Updated - Thanks Useless Code for the helpful suggestion, I have modified the code accordingly to use onSubmit instead of the onClick event.
Your HTML code should be:
<form align="center" method="POST" action="TARGET-PAGE-TO-HANDLE-DATA" name="regform" onsubmit="return Submit();">
The action attribute specifies the target page to handle the form data. And the onSubmit attribute specifies the Javascript function to be executed when the submit button in the form is clicked.
As already stated in a comment, onsubmit is much more appropriate in this situation. The JavaScript placed in an onclick attribute will fire when the HTML element is clicked, but for a form you actually want code that executes on submission. So:
<form align="center" method="POST" action="self" name="regform" onsubmit="Submit()">
would be closer. However, it's generally considered poor practice to use the "on" attributes to handle events in JavaScript. For one, it mixes your JavaScript with your semantic HTML, which can be make debugging harder an mixes separate concerns. But it also means that whatever you use in the "on" attributes has to be in the global scope, which can become problematic fast. Consider if you had multiple forms on the page; how would you designate the submit functions for each?
A more solid way of performing this is to put your function in an event listener, e.g.:
function Submit() {
// rest of your code here
}
document.form.regform.addEventListener('submit', Submit, false);
Here the addEventListener method takes an event type string first and a function to execute when that event occurs second. The MDN article on addEventListener has more.
I have this form:
<form action="../scrapll_m_nonstatic/process/reg/signup_process.php" method="post" name="signUp" onsubmit="return signUpVal()">
<div id="fieldHolder">
<input type="text" id="accountFieldFirstName" class="accountField" name="firstName" placeholder="First Name" />
<input type="text" id="accountFieldLastName" class="accountField" name="lastName" placeholder="Last Name" />
<input type="text" id="accountFieldUsername" class="accountField" name="username" placeholder="Username" />
<input type="text" id="accountFieldEmail" class="accountField" name="email" placeholder="Email Address" />
<input type="password" id="accountFieldPassword" class="accountField" name="password" placeholder="Password" />
</div>
<div id="subFooter">
<a data-ftrans="slide reverse" href="index.php" id="signUpButton">Sign In</a>
<a data-ftrans="slide" href="forgot.php" id="forgotButton">Forgot password</a>
</div>
<div id="footer">
<input type="submit" id="signIn" value="Sign Up" />
</form>
And I have this JS form validation script to check if the forms are empty:
function signUpVal()
{
var firstName = document.forms["signUp"]["firstName"].value;
var lastName = document.forms["signUp"]["lastName"].value;
var userName = document.forms["signUp"]["userName"].value;
var email = document.forms["signUp"]["email"].value;
var password = document.forms["signUp"]["password"].value;
if (firstName == null || lastName == "" || lastName == null || lastName == "" || userName == null || userName == "" || email == null || email == "" || password == null || password = "")
{
alert("Please fill out the form completely");
return false;
}
}
It doesn't do anything and goes directly to the action PHP script. How can I fix that?
You have two mistakes:
1). Name of the user name input does not match in JS code. Fix it to this:
<input type="text" name="userName" id="accountFieldUsername" class="accountField" placeholder="Username" />
instead of name="username"
2). Check your values like this:
if (firstName == "" || lastName == "" || userName == "" || email == "" || password == "") {
alert("Please fill out the form completely");
return false;
}
Also you don't need == null checks because form element value cannot be null, it's empty string if left blank.
Demo: http://jsfiddle.net/tn4A6/
I think this might be your problem.
You are using assignment operator = instead of comparison operator ==.
Your if condition should be:
if (firstName == null || lastName == "" || lastName == null || lastName == "" || userName == null || userName == "" || email == null || email == "" || password == null || password == "")
{
alert("Please fill out the form completely");
return false;
}
The last "=" (as opposed to "==") in the if (firstName == null .. etc ) statement was seen as a syntax error by IE, so the whole script didn't compile.
Firefox said the same thing, but surprisingly neither of them highlighted it with a popup. Only visible when you click F12 for debugger.
This meant the function signUpVal() didn't compile, so it didn't exist so far as the page was concerned - so the form just submitted.
dfsq's answer provides the rest