Enable Submit after password validation - javascript

In Profile Section of the user the password field is not mandatory however I set a function which calls the password validation.
Password and Confirm Password Field
<input type="password" id="password" name="password" class="form-control" onfocus="submission()">
<input type="password" id="cpassword" name="password_confirmation" class="form-control" onfocus="submission()">
Submission JS Function
function submission() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="password"]').keyup(function() {
if(passwordValidation()) {
$(':input[type="submit"]').prop('disabled', false);
}
});
}
Password Validation Function
function passwordValidation() {
$('input[type=password]').keyup(function() {
var pswd = $(this).val();
if (pswd != '') {
var x = document.getElementById("password").value;
var y = document.getElementById("cpassword").value;
if ( pswd.length < 8 ) {
$('#length').removeClass('valid').addClass('invalid');
} else {
$('#length').removeClass('invalid').addClass('valid');
}
//validate letter
if ( pswd.match(/[A-z]/) ) {
$('#letter').removeClass('invalid').addClass('valid');
} else {
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if ( pswd.match(/[A-Z]/) ) {
$('#capital').removeClass('invalid').addClass('valid');
} else {
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if ( pswd.match(/\d/) ) {
$('#number').removeClass('invalid').addClass('valid');
} else {
$('#number').removeClass('valid').addClass('invalid');
}
//validate symbol
if ( pswd.match(/[!##$%^&*]/) ) {
$('#symbol').removeClass('invalid').addClass('valid');
} else {
$('#symbol').removeClass('valid').addClass('invalid');
}
//validate symbol
if ( x == y && x != "" && y != "" ) {
$('#confirm').removeClass('invalid').addClass('valid');
} else {
$('#confirm').removeClass('valid').addClass('invalid');
}
return true;
} else {
return false
}
}).focus(function() {
$('#pswd_info').show();
}).focusout(function() {
$('#pswd_info').hide();
});
//return true;
}
The return of passwordValidation() is allows undefined not getting any false or true result. I tried multiple ways but no luck of success, anyone can help telling me what's wrong with the code.
The process of the password check is as following.
User should pass all conditions to turn on green then the submit button will be enabled otherwise if one or multiple conditions are not matched the submit button will be disabled. And if the inputs are empty it will be disabled as well. I don't want to allow the submission before setting the right password and confirming it.

Related

How to prevent form from sending when there are alerts showing? JavaScript

I created a contactus form on my website, and I have few js functions that check if the values are valid or not. What currently happens is - the functions do work, they check what they are supposed to, and the alert shows as well - But after all the alerts showed, it still submits the form.
I tried to use the Prevent method, and the window.back.history but none worked...
How can I fix it?
JavaScript part:
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
e.preventDefault();
window.history.back();
}
}
document.getElementById("gender").addEventListener('click',checkradio);
function checkradio() {
if(document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false ){
alert("Please select your gender");
return false;
e.preventDefault();
window.history.back();}
}
function checkbox(){
if (document.querySelector('#cbr:checked') == null){
alert("Please choose a subject");
return false;
e.preventDefault();
window.history.back();
}
function agecheck(){
var x = document.forms["contactus"]["age"].value;
var y = 18;
if(x<y)
{
alert("Please submit the form only if you're 18 yo");
return false;
e.preventDefault();
window.history.back();
}
}
}
</script>
My HTML part uses the submit method and links to:
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="validateForm1();checkbox();checkradio();agecheck()" style="float:right;text-align: right; direction: rtl;">
I think you can put 'return' in 'onsubmit'.
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
}
if (document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false) {
alert("Please select your gender");
return false;
}
if (document.querySelector('#cbr:checked') == null) {
alert("Please choose a subject");
return false;
}
var x = document.forms["contactus"]["age"].value;
var y = 18;
if (x < y) {
alert("Please submit the form only if you're 18 yo");
return false;
}
}
</script>
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="return validateForm1();" style="float:right;text-align: right; direction: rtl;"></form>
In your form for each you can use the required tag so they always have to input something into the field.
For example
<input type="text" id="username" name="username" required>

Verify form inputs with Javascript before send it with POST

I'm trying to verify some inputs inside a form with javascript before send it with POST to a PHP controller.
the JS code looks like this, verifyng cellphone number, email, and password:
function registerUser(){
// Validate Email
event.preventDefault();
function validateEmail(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);
}
function validate()
{
var email = document.getElementById("emailReg").val();
if (validateEmail(email))
{
var celular = document.getElementById("cellReg").val();
if(celular.lenght >= 10 && /[0-9]/.test(celular))
{
var pass = document.getElementById("passwordReg").val();
if(pass.length >= 6 && /[a-zA-Z]/.test(pass))
{
alert("correct data");
document.forms['registerForm'].submit();
}
else
{
// document.forms['registroForm'].submit();
event.preventDefault();
alert("password need to has at leas 6 characters and one uppercase");
}
}
else
{
event.preventDefault();
alert("Phone number must not have letters");
}
}
else
{
event.preventDefault();
alert("Incorrect e-mail");
}
return false;
}
}
this is the Form:
<form class="form row" method="POST" name="registerForm">
<input type="email" class="form-reg" name="emailReg" id="emailReg" placeholder="example#email.com" style="width:140px;" required>
<input type="text" class="formulario-registro" name="cellReg" id="cellReg" placeholder="cellphone number" style="width: 130px;" required>
<input type="password" class="formulario-registro" name="passwordRegistro" id="passwordRegistro" placeholder="contraseña" style="width: 140px;" required>
<button type="button" class="btn btn-round btn-qubit title" onclick="registroUser();">Registrarme</button>
</form>
I have to check the lenght and if the password has at least one uppercase, with the cellphone number if it has only numbers and at least 10 characters, if i write the type="number" property in the input tag it will appear with up and down arrows which i don't want to show, i could put the conditions in my php butin that way the form will get erased when i submit it and that's what i don't want to do.
Use the following CSS for this issue
if i write the type="number" property in the input tag it will appear with up and down arrows which i don't want to show
/* Hide Up and Down arrows. */
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
I apply function on submit for the form... when it's submitted the JS code below verify if the conditions are true and then it is sended to the php controller.
$(document).ready(function(){
$(".registerForm").on('submit', function(event)
{
var validate = validate();
if(validate === "success")
{
console.log("success");
document.forms['registerForm'].submit();
}
else{
event.preventDefault();
}
});
// validate password //
function validate()
{
var email = $("#emailRegister").val();
if (validateEmail(email))
{
var cell = $("#cellRegister").val();
if(cell.length === 10)
{
var pass = $("#passwordRegister").val();
if(pass.length >= 6 && /[A-Z]/.test(pass))
{
console.log("correct data");
return "success";
}
else
{
alert("password must have a lenght of 6 digits and at least one capital letter");
return "false";
}
}
else
{
alert("cellphone must be minimum a 10 digits number");
return "false";
}
}
else
{
alert("incorrect e/mail adress");
return "false";
}
}
// Validate Email
function validateEmail(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);
}
});

How to validate form both on submit and keyup

My form validates on keyup, but when I try to validate it on submit too I just can't think what to do.
This is my HTML:
<form action="#" method="post">
<section class="col">
<section class="row">
<label for="name">Name</label>
<input type="text" name="name" value="" id="name" class="field validate-field valid-name" />
</section>
<section class="row">
<label for="email">Email Address</label>
<input type="text" name="email" value="" id="email" class="field validate-field valid-mail" />
</section>
<section class="row">
<label for="phone">Phone Number</label>
<input type="text" name="phone" value="" id="phone" class="field validate-field valid-phone" />
</section>
</section>
<section class="col">
<label for="message">Message</label>
<textarea class="field validate-field valid-text" name="message" id="message-field"></textarea>
<input type="submit" value="Submit" class="submit-button" />
</section>
</form>
JS:
function validate( field ){
var value = field.val();
var to_label = field.parent().find('label');
var error = false;
var error_message = '';
to_label.find('span').remove();
if ( field.hasClass('validate-field') && value == '' ) {
error = true;
error_message = 'Empty Field';
} else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
error = true;
error_message = 'Name must consist characters only';
} else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
error = true;
error_message = 'Invalid Email';
} else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
error = true;
error_message = 'Your phone must be digits only';
};
if ( error == true ) {
to_label.append('<span>'+ error_message +'</span>');
}
};
$('.validate-field').live('keyup', function(){
validate( $(this) );
});
function valid_name(value){
var valid = /^([a-zA-Z_\.\-\+])+$/;
return valid.test(value);
};
function valid_email(value){
var valid = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return valid.test(value);
};
function valid_phone(value){
var valid = /^[0-9-+]+$/;
return valid.test(value);
};
And I have to add something like this:
$('form').live('submit', function(){
if ( "...validated..." ) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
What should be in the submit function?
I have tried:
$('form').live('submit', function(){
var valid = validate( $('.field') )
if ( valid == true ) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
But this validates all the forms with all the validation (e-mail, phone ...). I have tried in validation() function to add if (error == false){ return: true }, then in submit function ran validation() and added if ( validation() == true ){ .. to send php ..}. That didn't work too. What I need to do ?
I guess you can validate the whole form by:
function validateAll() {
var valid = true;
$('form').find('.validate-field').each(function (i, e) {
if (!validate($(this))) {
valid = false;
return;
}
});
return valid;
}
function validate( field ){
var value = field.val();
var to_label = field.parent().find('label');
var error = false;
var error_message = '';
to_label.find('span').remove();
if ( field.hasClass('validate-field') && value == '' ) {
error = true;
error_message = 'Empty Field';
} else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
error = true;
error_message = 'Name must consist characters only';
} else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
error = true;
error_message = 'Invalid Email';
} else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
error = true;
error_message = 'Your phone must be digits only';
};
if (error) {
to_label.append('<span>'+ error_message +'</span>');
}
return !error;
};
$('form').live('submit', function(){
if (validateAll()) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
That's the option which requires the smallest amount of refactoring, on my opinion.
Just let me explain you what the function validateAll does. It finds all fields with class validate-field and pass it as argument to the validate function. Because of the refactoring I made in validate it returns false if the field is not valid so when we call validate with specific input and it's invalid we just return false (the form is not valid).
Here is an example in JSfiddle.
For more advance validation I can recommend you validation plugins like: http://docs.jquery.com/Plugins/Validation or jqxValidator.
You are almost done. Just add below code, it'll work
$('form').submit(function(){
var field = $(this).find('.validate-field');
validate( field );
});
Hope this will solve your issue.
Fiddle: http://jsfiddle.net/r1webs/cFeCx/

Javascript Coding in HTML

For an assignment I have I am writing a registration form. My question is how would I connect the first statement, and the function below so when someone types in their email in the text box it checks to see if the email is valid? (document.getElementById('user').value)
<input id="user" type="text" onblur="isUserNameValid();"></input><br/>
function isEmailValid(email) {
"use strict";
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[\w.-]/;
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
As you confirmed you can use HTML5, simply change your input to the below and the browser will validate the email for you when the form is submitted.
<input id="user" name="user" type="email" /><br/>
N.B. You can use a self closing tag for an input. You should also assign the name attribute of the input as that is what is used as the key for the data when it is submitted to the server.
<input type="text" id="email" name="email" onblur="javascript:return validate();"/>
<script>
function validate() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.getElementById("email").value;
if (reg.test(address) == false) {
alert('Invalid Email Address');
return false;
} else {
alert('valid Email Address');
return false;
}
}
</script>

Single else clause for multiple if clauses - javascript

First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.

Categories

Resources