Javascript - A problem with the validation of my form - javascript

I have a problem with the validation script of my php form to send an email, and although it works very well to validate the form, when the user clicks on the "accept" button of the alert, the script does not block the action, and the form is sent anyway...
What am I doing wrong?
Thanks in advance!
HTML:
<div id="form">
<section>
<form action="send.php" method="post" accept-charset='UTF-8'>
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND" onclick="validate(this);">
</div>
</form>
</section>
</div>
SCRIPT (validation):
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
}

Change the event to onsubmit and put it on the form.
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
console.log('passed!');
}
<div id="form">
<section>
<form action="" method="post" accept-charset='UTF-8' onsubmit="return validate(this);">
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND">
</form>
</section>
</div>

Related

Can I Validate Two Fields Instead of One Field With This JavaScript?

I use the javascript below to validate the Phone Number field on my form by showing the next hidden field whenever the value the user inputs in the phone number field on my form matches with the values in my javascript.
however, if their input does not match with the values in my javascript, the hidden field remains hidden and the user will be unable to submit the form.
The javascript works fine for the phone field but I am trying to validate two different fields to match with the values in my javascript.
For example, I want to make the values users input on the phone field and the email field of my form match with the values in my javascript before the hidden field shows.
Illustration below;
Lets say, the values in my javascript are; if (phone === "12345" && email === "12345#gmail.com")
If the user inputs Phone: 12345 and their email: 12345#gmail.com, the hidden field shows.
If the user inputs Phone:123 and their email: 12345#gmail.com, the hidden field remains hidden.
I have tried different solutions to validate the phone and email field but all my solutions failed and I need some help with this.
Sorry if my solution below is poor but I am not the owner of the original code.
Thanks for your help.
Below is my sample code for the phone field validation. (WORKING FINE!)
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isPhoneInUse(value)) {
$(".validate").show();
} else {
alert ("Phone do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone").val();
if (isPhoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return false;
}
})
function isPhoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<div class="validate"><span style="color: red;"><b>Phone Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>
Below is my solution to validate the phone and email fields. (NOT WORKING!)
$('.validate').hide();
$('body').on('blur', '#phone', '#email', function() {
var value = $(this).val();
if (isDataInUse( $("#phone").val(), $("#email").val() )) {
$(".validate").show();
} else {
alert ("Phone and Email do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone" && "#email".val());
if (isDataInUse( $("#phone").val(), $("#email").val() )) {
// validation failed. cancel the event
console.log("not submitting");
event.preventDefault();
}
})
function isDataInUse(phone, email) {
return (phone === "1234" && email === "1234#gmail.com")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<div class="validate"><span style="color: red;"><b>Phone and Email Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>
After many corrections, here is a working snippet:
$('.validate').hide();
$('#phone, #email').on('change', function() {
let phone = $('#phone').val();
let email = $('#email').val();
if (isDataInUse(phone, email)) {
$(".validate").show();
} else {
alert ("Phone or Email do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#theForm').on('submit', function(e) {
let phone = $('#phone').val();
let email = $('#email').val();
if (isDataInUse(phone, email)) {
// validation failed. cancel the event
console.log("not submitting");
e.preventDefault();
return false;
}
})
function isDataInUse(phone, email) {
return (phone === "1234" && email === "1234#gmail.com")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="theForm">
<div class="validate"><span style="color: red;"><b>Phone and Email Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>

onSubmit redirect to website depenfing on value

Hi I'm trying to create a simple login form with 2 or 3 users where depending on who is logging in the redirect should be to different urls.
My code so far:
HTML
<h1 class="title">Logga in</h1>
<div class="grid__container">
<form name="login" onSubmit="return validateForm();" action="some website url" method="post" class="form form--login">
<div class="form__field">
<label class="fontawesome-user" for="login__username"><span class="hidden">Username</span></label>
<input name="usernameInput" id="login__username" type="text" class="form__input" placeholder="Username" required>
</div>
<div class="form__field">
<label class="fontawesome-lock" for="login__password"><span class="hidden">Password</span></label>
<input name="passwordInput" id="login__password" type="password" class="form__input" placeholder="Password" required>
</div>
<div class="form__field">
<input type="submit" value="Sign In">
</div>
</form>
</div>
JavaScript
function validateForm() {
var username = document.login.usernameInput.value;
var password = document.login.passwordInput.value;
var username1 = "user 1";
var password1 = "1234";
var username2 = "user 2";
var password2 = "4321";
if ((username == username1) && (password == password1)){
return "www.google.se";
}else if (username == username2) && (password == password2) {
return "www.facebook.se";
}else{
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}

Validate Textbox Javascript

Here is the following code, I am learning Javascript on my own and wanted to know how I could validate my code to make the textboxes say something like "please enter a value" or "please enter a valid Username or password.
I've attempted, but this is as far as online searching that I have done for it.
<head>
<script type = 'text/javascript'>
function nullcheck()
{
if(document.getElementById("").value==="")
{
alert("Please enter value.");
return false;
}
}
</script>
<title>Login Form</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="container">
<div class="login">
<h1>Login</h1>
<form method="post" action="index.xhtml">
<p><input type="text" name="login" value="" id="Username or Email" /></p>
<p><input type="password" name="password" value="" id="Password"/></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me"/>
Remember me on this computer
</label>
</p>
<p class="submit"><input type="submit" name="commit" value="Login" onchange="nullcheck()"/><button type="reset" value="Clear">Clear</button></p>
</form>
</div>
</section>
</body>
</htm
You can validate items one at a time, but a more general solution is to write a validate() function. Make your form element look like this:
<form method="post" action="index.xhtml" onsubmit="return validate();">
If the validate() function returns false, the form will not be submitted. It is up to the validate() function to issue prompts, etc.
Sample function:
function validate() {
var error = false,
errmsg="";
if(document.getElementById("username").value==="") {
error = true;
errmsg = "User name may not be blank.\n";
}
if(document.getElementById("password").value==="") {
error = true;
errmsg = "Password may not be blank.\n";
}
if (error) {
alert(errmsg);
return false;
} else {
return true;
}
} // validate

javascript how to create a validation error message without using alert

I am looking to make a simple form validation error message that displays under the username field.
I cannot seem to figure it out.
<form name ="myform" onsubmit="validation()">
Username: <input type ="text" name="username" /><br />
<input type ="submit" value="submit" />
<div id ="errors">
</div>
</form>
Here is my validation script:
function validation(){
if(document.myform.username.value == ""){ //checking if the form is empty
document.getElementById('errors').innerHTML="*Please enter a username*";
//displaying a message if the form is empty
}
You need to stop the submission if an error occured:
HTML
<form name ="myform" onsubmit="return validation();">
JS
if (document.myform.username.value == "") {
document.getElementById('errors').innerHTML="*Please enter a username*";
return false;
}
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
I would strongly suggest you start using jQuery. Your code would look like:
$(function() {
$('form[name="myform"]').submit(function(e) {
var username = $('form[name="myform"] input[name="username"]').val();
if ( username == '') {
e.preventDefault();
$('#errors').text('*Please enter a username*');
}
});
});

Why does this form submit on click of the submit button

<script type="text/javascript">
var geid = function(x) {
var element = document.getElementById(x);
return element;
}
function submitForm(){
var password = geid('password').value;
var passwordConfirm = geid('passwordConfirm');
//THIS IS OF HIGH IMPORTANCE THAT THIS CONFIRM PASSWORD MATCHES
//WILL NEED TO VALIDATE IT IN THE PHP AS WELL>
else if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
else if (passwordConfirm == "") {
registerMessage.innerHTML = "Please confirm your password.";
return false;
}
else if (passwordConfirm != password) {
registerMessage.innerHTML = "Your passwords don't match.";
return false;
}
else {
registerMessage.innerHTML = "Taking you to your profile, please wait a moment...";
document.forms['registerform'].submit();
}
}
<form method="post" action="register.php" id="registerform" onsubmit="return submitForm()">
<label for="password" class="registerLabel">Password</label>
<input type="password" name="password" id="password" class="registerText" /> <br />
<label for="passwordConfirm" class="registerLabel">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm" class="registerText" /> <br />
<div class="submitMessage">
<input type="submit" id="submit" name="submit" value="Register" class="registerButton cleangray" /><br />
<div id="registerMessage"><?php echo $error ?></div>
</div>
<div class="clear"></div>
</form>
You can't start with else if; you need to start with if
if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
That's preventing any of your validation code from running and just submitting the form using the standard submit mechanism.
This also isn't the best way to approach the validation. Rather than return at each error, you could build up a string of messages and report them all back in one go. That way the user knows everything that's wrong — your current method will only ever set one message.
Because you have error in JavaScript, you are using else if without defining if first. Because of this error all JavaScript code fail.
Change
else if (password == ""){
to
if (password == ""){
Working demo http://jsfiddle.net/Zs3km/
BTW in your code HTML is within <script> tag, not sure if its your mistake just here. You have to close <script> tag before <form> tag is opened.

Categories

Resources