Javascript form validation not loading PHP page - javascript

I have the following form in a PHP page
<form action="login.php" method="post">
School: <input type="text" name="schoolInput"><div id="erschool"></div><br>
Username: <input type="text" name="usernameInput"><div id="eruser"></div><br>
Password: <input type="text" name="passwordInput"><div id="erpass"></div>
<input type="button" name="loginSubmit" value="submit" onclick="return validateLogin()">
</form>
My validation looks like this
function validateLogin() {
var school = document.getElementsByName("schoolInput")[0].value
var username = document.getElementsByName("usernameInput")[0].value
var password = document.getElementsByName("passwordInput")[0].value
var failed = false;
if(!school){
document.getElementById("erschool").innerHTML = "No school entered";
failed = true;
}
if(!username){
document.getElementById("eruser").innerHTML = "No username entered";
failed = true;
}
if(!password){
document.getElementById("erpass").innerHTML = "No password entered";
failed = true;
}
if(failed){
return failed;
}
return true;
}
The JS in the validation works as it activates the error messages. However, if the form is completed correctly, it doesn't load login.php as it should.
I'm running the app on Heroku for testing.
What am I doing wrong?

You need to use <button type=submit"> to submit the form. Also, you can move the validation into the form. i.e.:
<form action="login.php" method="post" onclick="return validateLogin()">
School: <input type="text" name="schoolInput"><div id="erschool"></div><br>
Username: <input type="text" name="usernameInput"><div id="eruser"></div><br>
Password: <input type="text" name="passwordInput"><div id="erpass"></div>
<button type="submit" name="loginSubmit" value="submit">
</form>
Also, your validation function is wrong - it will always return true (so the form will always be submitted):
if(failed){
return failed; // if failed is true, then return TRUE...
}
return true; // ....otherwise return TRUE!!
I presume you mean to return !failed so if failed is true then you return false?
You don't actually need to check the value for failed either- you can just return !failed:
if failed is true, then !failed will return false so the form is not submitted
if failed is false, then !failed will return true so the form is submitted

How to make it work
What you probably wanted to achieve is:
<button type="button" onclick="if(validateLogin()) this.form.submit()">
This way, your form only gets submitted if the function returns TRUE. (Which, as #FluffyKitten pointed out, will always be the case so you have to fix the validation function too.)
There are more than one ways to validate a form. My favorite is giving the form an onsubmit handler, and the syntax you used on the button looks like you were trying to mix this technique with the button-click validation method. Form onsubmit way looks like this:
<form onsubmit="return validateLogin()">
...
...
<button type="submit">
</form>
These are 2 separate ways.
Method 1: form onsubmit=return valid() + button type=submit
Method 2: form + button type=button onclick=if(valid()) submit()
Improve validateLogin
I'd suggest some refactoring here, both for readability and ease of use.
function validateLogin() {
var checkEmpty = function(name) {
var element = document.getElementsByName(name+"Input")[0];
if(element.value !== "") return false; // return if not empty
var errorField = document.getElementById("er"+name);
errorField.innerHTML = "No value for "+name;
return true;
}
if(checkEmpty("school" )) return false;
if(checkEmpty("username" )) return false;
if(checkEmpty("password" )) return false;
return true;
}

Related

Regex always returning either always true or always false regardless of valid test value

I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.
HTML:
<form name="newform" action="Create.php" onsubmit="return validateForm()" method="POST" >
Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
JavaScript:
<script type="text/javascript">
function validateForm(){
var CodePattern = new RegExp(/\b\d{5}\b/);
if(CodePattern.test(document.forms["newform"]["code"].value) == true)
{
return true;
}
else
{
return false;
}
}
function CodeStyleRefresh(){
document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>
Some other ways I have tried to specify the expression:
var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';
This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.
UPDATE:
I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:
function validateForm(event)
{
console.log("Im running the script!");
console.log(event.target.querySelector("[name=code]").value);
var CodePattern = new RegExp(/\b\d{5}\b/);
var codeVal = event.target.querySelector("[name=code]").value;
if(CodePattern.test(codeVal) == true)
{
alert("Expression Passed!");
}
else
{
alert("Expression Failed!");
return false;
}
}
My HTML is now:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
Still this expression is only hitting the failed state and alerts expression failed.
If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!
Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?
Try a context aware piece of code, update your html to:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
And your javascript:
function validateForm(event){
var myRegex = new RegExp(/\b\d{5}\b/);
//event.target holds the node element that triggered the function in our case, the Form itself
var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event
return myRegex.test(myValue) //return true if it passed, false if not
}
Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
var CodePattern = /\b\d{5}\b/;
// comment below line after testing
evt.preventDefault();
if(CodePattern.test(codeVal) == true)
{
console.log("Expression Passed!");
return true;
}
else
{
console.log("Expression Failed!");
return false;
}
}
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="abc 12345 foo bar" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.
I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
console.log("Code Value: " + String(codeVal));
// comment below line after testing
evt.preventDefault();
var lenPass = false;
var strlen = codeVal.length;
if(strlen == 5)
{
lenPass = true;
}
if(lenPass)
{
var c1 = Number.isNaN(Number(codeVal.charAt(0)));
var c2 = Number.isNaN(Number(codeVal.charAt(1)));
var c3 = Number.isNaN(Number(codeVal.charAt(2)));
var c4 = Number.isNaN(Number(codeVal.charAt(3)));
var c5 = Number.isNaN(Number(codeVal.charAt(4)));
console.log(c1);
console.log(c2);
console.log(c3);
console.log(c4);
console.log(c5);
var pass = true;
if(c1)
{
pass = false;
}
if(c2)
{
pass = false;
}
if(c3)
{
pass = false;
}
if(c4)
{
pass = false;
}
if(c5)
{
pass = false;
}
if(pass)
{
alert("Expression Stage 2 Passed!");
return true;
}
else
{
alert("Expression Stage 2 Failed!");
return false;
}
}
else
{
alert("Expression Stage 1 Failed!");
return false;
}
}
<html>
<head>
</head>
<body>
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
</body>
</html>

Javascript - how to prevent form from sending with multiple validation checks?

It seems that you can prevent a form from sending if your validation check returns false.
I have:
<form name="registration" action="registration.php" onsubmit="return validate()">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
My validate() function in my javascript is made of multiple different checks though.
function validate() {
checkUsername();
checkPassword();
checkFirstname();
checkLastname();
checkBirthdate();
checkEmail();
checkPhone();
}
There might be a case where the user inputs valid data for all of them except one. If that's the case, how do I tell validate() to still send 'false' back to the form, so that it doesn't submit?
Edit: If anyone is still reading this, for some reason my form is still sending. I even changed my validate() function so the only statement is "return false;" Do I have a syntax error or something?
Edit2: I found another solution that is simple, even if a little archaic. It overcame an issue I had where the function was only evaluating the first check and returning.
function validate() {
var truth1 = checkUsername();
var truth2 = checkPassword();
var truth3 = checkFirstname();
var truth4 = checkLastname();
var truth5 = checkBirthdate();
var truth6 = checkEmail();
var truth7 = checkPhone();
return (truth1 && truth3 && truth5 && truth2 && truth4 && truth6 && truth7);
}
all your individual field validation functions should return a boolean.
then your overall form validation function will be
function validate() {
var checks = [
checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone,
].map(function(check) { return check(); });
return (checks.indexOf(false) === -1);
}
now ur validate function will return false if any field is invalid. true if all fields are valid
You can use Array.prototype.every() to call each function, if any function returns false, false will be returned from .every() call
<form name="registration" action="registration.php">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
function validate() {
return [checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone].every(function(check) {return check()});
}
document.querySelector("[name=registration]")
.onsubmit = function(event) {
event.preventDefault();
if (validate()) { this.submit() }
else { // notify user which fields are invalid }
}
The "validate" function needs to return a "true" boolean result only when ALL of the individual check functions return a "true" result.
One way to do this is to modify each line in the current "validate" function to something like the following code.
bUsernameSts = checkUsername();
if !bUsernameSts { return false };
...
<other checks>
...
return true;
The only way the new "validate" function can return "true" is if all of the individual input validation checks were successful.

How to Validate form without submitting it

I have a form that I want to validate before the form submits, when I press the Submit button. I know I am supposed to use preventDefault but I am not sure how to use it correctly:
function validateName() {
var name = form.firstname.value;
if (name == "") {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else if (/[0-9]/.test(name)) {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else {
document.getElementById("firstnameInvalid").style.visibility = "hidden";
}
}
<form name="form" method="post" onsubmit="return validate(this)">
<p>First Name:
<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name" />
<span id="firstnameInvalid" style="color:red; visibility:hidden"> Name is Invalid </span>
</p>
You can stop the form by adding return statement to your validation code. onsubmit will stop the form submit when the function returns false.
your validate() must return a true or false value to it work with onsubmit="return validate(this)"
try something like
function validate(variable)
{
if(condition) //add a condition to validate
{
return false; //if condition are met, return false and do not submit
}
//you can create more than one condition following this logic.
return true; //if none of the conditions are met, he return true and submit
}
As others have said, returning false in your onsubmit callback will prevent the form from being submitted.
var form = document.getElementById( 'idgoeshere' );
form.onsubmit( function() {
// validate here
return false;
});

Process a form with javascript and use it in pop up?

Theres a form on a website I'm trying to make and I was wondering if there was a way to click the submit button for the form and then have a pop up use that information
sorry for the newb question, code is kind of like this:
<form name="myform" onsubmit="submitform()" type="POST">
Username: <input type="text" name="username">
<a>
<input type = "submit" value = "Submit"
</a>
</form>
<script type="text/javascript">
function submitform()
{
username = document.getElementsByName("username")
window.alert("hi:" username)
}
</script>
Yeah, there's a few issues with your code, but you're close.
Submit buttons shouldn't be inside of <a> tags. You're also missing the closing carrot here.
You're using type, but I'm guessing you meant method.
In your JavaScript, you're getting an array of elements with getElementsByName and never getting the value.
Put that all together, and:
<form name="myform" onsubmit="submitform()" method="POST">
Username: <input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
<script>
function submitform()
{
username = document.getElementsByName("username")[0].value
window.alert("hi:" username)
return false;
}
</script>
You can try this:
<form name="myform" onsubmit="submitform(this) return false;" type="POST">
then in your function:
function submitform(form)
{
username = document.getElementsByName("username")
window.alert("hi:" username)
}
Then use the form object your passing in.
if ($(form).valid())
{
var fields = $(form).serializeArray();
$(fields).each(function ()
{
if (this.name !== undefined)
{
var propertyName = this.name;
var propertyValue = this.value;
//Do something
}
});
}

Form only validates one field with javascript

I'm trying to make a simple register form that makes sure the username and password have been entered correctly before submitting. Here's my form:
<form id="register" name="register" action="" method="POST" onsubmit="return validate_account_creation(this)">
<label> Username
<input type="text" name="username" />
</label>
<label> Password
<input type="text" name="password" />
</label>
<input type="submit" name="submit" value="Submit" class="button"/>
</form>
And here are my javascript functions:
function validate_username(username) {
var regex = /[a-zA-Z0-9\-\_]{5,15}/g;
var str = username;
if (!regex.test(str)) {
alert("Your username must be between 5 and 15 characters in length");
register.username.focus();
return false;
}
}
function validate_password(password) {
regex = /[a-zA-Z]{5,}[0-9]{1,}/g;
str = password;
if (!regex.test(str)) {
alert("Your password must be at least 6 characters in length and must contain at least 1 number");
register.password.focus();
return false;
}
}
//Validate register form
function validate_account_creation(form) {
return validate_username(form.username.value);
return validate_password(form.password.value);
return true;
}
The username function works fine and it validates that one every time. However, if the username is correct, the form submits. The second function never activates. If the first function doesn't return anything, shouldn't the second function then be called and validate the second field?
It's the return statements. A return aborts the rest of the function and returns the result, so your validation should look like:
Javascript
function validate_account_creation(form) {
var username = validate_username(form.username.value);
var password = validate_password(form.password.value);
return username && password; // if both are true, submit form
}

Categories

Resources