Unable to stop form from submitting when validating an email - javascript

I am making a simple form that takes the value from a text input, checks if all the characters that are in an email address are there and returns true or false. According to a lot of different resources, if it returns false, then the form shouldn't be submitted. However, when I test it in JS bin, it submits it. Here's the code:
function validateEmail(x) {
console.log(x);
var email = x.myText.value;
console.log(email);
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
console.log(re.test(email));
}
<form name="myForm" onsubmit="return validateEmail(this)">
<input name="myText" type="text">
<input type="submit" value="Submit">
</form>

you need to return false if the validation fails, so simply replace
console.log(re.test(email));
with
return re.test(email);
Demo

Try this:
function validateEmail(x) {
console.log(x);
var email = x.myText.value;
console.log(email);
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}

Change <form name="myForm" onsubmit="return validateEmail(this)">
With this <form name="myForm" onClick="return validateEmail(this)">
And function is like this
function validateEmail(x) {
console.log(x);
var email = x.myText.value;
console.log(email);
var re = your regular expression;
if((re.test(email)){
document.getElementById(myForm).submit();
}

Related

Javascript form validation not loading PHP page

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;
}

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>

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
}

JavaScript Is Text Box Empty?

How can I check if a input field is empty in JavaScript when submitting the form?
html:
<input type="text" name="start_name" id="start_name">
Refer to http://www.w3schools.com/js/js_form_validation.asp
Have your form tag as
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Next, have a javascript function
<script>
function validateForm()
{
var x=document.forms["myForm"]["start_name"].value;
if (x==null || x=="")
{
alert("Start name must be filled out");
return false;
}
}
</script>
var start_name = document.getElementById('start_name');
if( start_name.value.length > 0 ){
// Then there is something there.
}
Try.
<script type="text/javascript">
function checkme()
{
var inputVal = document.getElementById("start_name").value;
if(inputVal == "")
{
//code
}
}
</script>
<form action="" method="post" onSubmit = "checkme();">
<input type="text" name="start_name" id="start_name">
</form>
Just checking 'if (x==null || x=="")' is not enough to validate empty text box. Go for RegEx to check empty text box.
/^\s*[0-9a-zA-Z][0-9a-zA-Z ]*$/
Ensures that at least one character is not whitespace and is of one of the allowed characters.
Use /[a-z]/i as this regex will only match if there is at least one alphabetical character.
<form action="someActionUrl" onsubmit="return validate('first_name')">
<input id="first_name" name="first_name" />
</form>
<script>
function validate(inputId){
var val = document.getElementById(inputId).value;
if(val.length>0){
// do something
return true;
}
return false;
}
</script>
try this:
var x = document.getElementById("start_name");
if(x.value== "")
{
//your restriction code comes here
}
else
{
//go ahead!
}
Note: please check for syntax if its proper.i am writing the code here directly,haven't checked it on IDE.

Categories

Resources