Angular: unable to avoid form submit on validation failure - javascript

Im trying to validate the following form:
<div ng-controller="LoginController">
<form name="form" class="ng-pristine ng-valid" accept-charset="UTF-8" action="/sessions/login?locale=" method="post" novalidate>
{{ errorUsername }}
<input id="username" name="username" type="text" placeholder="EMAIL ADDRESS" ng-model="username" required>
{{ errorPassword }}
<input id="password" name="password" type="password" placeholder="PASSWORD" ng-model="password" required>
<p><input name="commit" value="LOGIN" ng-click="submitForm()" type="submit"></p>
</form>
</div>
With the following method on LoginController:
$scope.submitForm = function() {
var is_valid = true;
if ( username.innerHTML == "" ) {
$scope.errorUsername = "Email required";
is_valid = false;
};
if ( password.innerHTML == "" ) {
$scope.errorPassword = "Password required";
is_valid = false;
};
if (! is_valid ) { $scope.form.submitted = true }
};
The form submition enters the method, and for a second you can see the the error messages are displayed. But the form is still submited.
I should add that the form is linked to a rails controller. But that shouldn't matter because my intention is never to call rail's controller action if the form has errors.
Thanks in advance.

All you need is to write return false;
$scope.submitForm = function() {
var is_valid = true;
if ( username.innerHTML == "" ) {
$scope.errorUsername = "Email required";
is_valid = false;
return false;
};
if ( password.innerHTML == "" ) {
$scope.errorPassword = "Password required";
is_valid = false;
return false;
};
if (! is_valid ) { $scope.form.submitted = true }
};

Try to replace
<input name="commit" value="LOGIN" ng-click="submitForm()" type="submit">
to
<input name="commit" value="LOGIN" ng-click="submitForm()" type="button">

You can try with this.
<form name="yourform" ng-submit="yourform.$valid && submitForm()"

This is is. Apparently you can't prevent default submit if the form has an action attribute:
Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
So, you have to trick it by adding some code in the form:
<form name="login" class="ng-pristine ng-valid" accept-charset="UTF-8" action="/sessions/login?locale=" method="post" novalidate ng-submit="(submitted=true) && login.$invalid && $event.preventDefault()" ng-class="{true:'submitted'}[submitted]">
Basically we used $event.preventDefault() to stop the submit propagation only if the form is invalid; plus we set a $scope variable ‘submitted’ to true in order to have a class that gets appended to the form if the form has been submitted in an invalid state at least once, even if none of its fields have been ‘touched’ – so it’s still ng-pristine.
Solution found here: http://sandropaganotti.com/2014/03/01/angular-js-prevent-an-invalid-form-submission/

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>

How do I check to see is password matches confirm password before user is allowed to submit the form JS

Basically I have a sign-up form , I want the password and confirm password field to match before the user is allowed to submit the form. I have the password and confirm password matching logic but do not know how to disable user from submitting if they do not match
This is my form in my html
<form action="/register" method="post" novalidate class="mt-4" class="form">
<div class="mb-3">
<label for="username" class="form-label">Company Name*</label>
<input type="text" class="form-control" required id="username" name="username"
placeholder="Facebook Ltd">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address*</label>
<input type="email" class="form-control" required id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="John#gmail.com" name="email">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password*</label>
<input type="password" class="form-control password" required id="password
placeholder="Min 8 Characters" name="password">
</div>
<div class="mb-3">
<label for="confirm-password" class="form-label">Confirm Password*</label>
<input type="password" class="form-control confirm-password" required id="confirm-password" placeholder="Must Match">
<span class="matching-txt mt-1">Not Matching</span>
</div>
<button class="confirm-pwd" type="submit" class="btn mt-3 submit-btn">Sign-up</button>
</form>
This is my logic to compare the password field and confirm password field on keyup
// Password and Confirmed passwords validation
let pwd = document.querySelector('.password');
let confirmPwd = document.querySelector('.confirm-password')
let matchingTxt = document.querySelector('.matching-txt')
let form = document.querySelector('.form')
function comparePwd() {
if (confirmPwd.value) {
if (pwd.value != confirmPwd.value) {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'red'
matchingTxt.innerHTML = 'Not Matching'
e.preventDefault()
} else {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'green'
matchingTxt.innerHTML = 'Matching'
}
} else {
matchingTxt.style.display = 'none'
}
}
confirmPwd.addEventListener('keyup' , () => {
comparePwd()
})
pwd.addEventListener('keyup' , () => {
comparePwd()
})
How do I do it in a way that if passwords do not match user cannot submit the form.
A HTML form element can take use of a special comparison function before submitting by populating its onsubmit attribute. That means the novalidate attribute must not be present.
Your comparePwd() function just needs a little tweak: it needs to return false, in case something is wrong - e.g. the passwords do not match.
So simply change the form to this:
<form action="/register" method="post" onsubmit="return comparePwd()" class="mt-4" class="form">
and the comparison function to this:
function comparePwd() {
if (confirmPwd.value) {
if (pwd.value != confirmPwd.value) {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'red'
matchingTxt.innerHTML = 'Not Matching'
return false
e.preventDefault()
} else {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'green'
matchingTxt.innerHTML = 'Matching'
}
} else {
matchingTxt.style.display = 'none'
}
}
Add this to your code
let submitBtn = document.getElementById("submitBtn");
and add id to the button to make it match:
<button class="confirm-pwd" type="submit" class="btn mt-3 submit-btn" id="submitBtn">Sign-up</button>
This way you can disable the button when the 2 fields do not match
if (pwd.value != confirmPwd.value) {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'red'
matchingTxt.innerHTML = 'Not Matching'
e.preventDefault()
submitBtn.disabled = true
} else {
matchingTxt.style.display = 'block'
matchingTxt.style.color = 'green'
matchingTxt.innerHTML = 'Matching'
submotBtn.disabled = false
}
Call your function comparePwd() on click on submit button:
<button onclick="comparePwd()" class="confirm-pwd" type="submit" class="btn mt-3 submit-btn">Sign-up</button>
after adding this onclick action to button, remove the event listeners both
confirmPwd.addEventListener('keyup' , () => {
comparePwd()
})
pwd.addEventListener('keyup' , () => {
comparePwd()
})

Javascript - A problem with the validation of my form

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>

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