Rails with HTML5 validation and JS - javascript

In my rails app I have validation form for matched email. For some reason validation doesn't worked - it shows error below form (when email addresses are not equal) but it submits the form and goes to the next page anyway.
validations.js
if (registrationsForm.length > 0) {
restrictZipCodeToNum();
restrictPhoneToNum();
submit.on('click', function(e) {
var invalidInput = $('input:invalid');
e.preventDefault();
if (emailField.val() !== emailConfirmationField.val() && emailField.length > 0) {
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
if (emailField.val() !== '') obligatoryInvalidMsg.hide();
}
validateEmail();
scrollToFirstInvalid();
if (invalidInput.length === 0 && !fileInput.hasClass('invalid')) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateInput();
}
});
}
new.html.erb
<div
class="col-sm-12 col-md-12 col-xs-12 text-center bank-employees-users-registration__registrations-submit--wrapper">
<%= submit_tag t('.submit'), class: "bank-employees-users-registration__submit-btn registrations" %>
</div>
Any idea? I put the debugger below the submit.on('click', function(e) { to check what is under invalidInput but it shows correct value - input:invalid. So maybe some form is overriding the whole logic, I don't know, any suggestions are welcomed.
Function of checking if email address are the same is here:
function validateEmail() {
$('input[type="email"]').change(function() {
if (emailField.val() === emailConfirmationField.val() && emailField.val() !== '') {
obligatoryInvalidMsg.hide();
emailInvalidMsg.hide();
emailField.removeClass("invalid");
emailConfirmationField.removeClass("invalid");
} else if (emailField.val() === emailConfirmationField.val() && emailField.val() === '') {
emailInvalidMsg.hide();
obligatoryInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
} else {
obligatoryInvalidMsg.hide();
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
}
});
}
EDIT
After debugging I think the main problem is in last if block -> if (invalidInput.length === 0 .... When I put debugger below this block and in console wrote invalidInput.length I will get 0 in case when first address in from is 123#example.com and the confirmation email address is 4321#example.com. When I have empty field it shows correctly as 1 or 2 (depends on empty field). No idea what's going wrong.

Take a look to Hemant Metalia response on this post
He mentions that's is important to use event.preventDefault() instead of e.preventDefault(), maybe it works for you.

Related

conditional statement for contact form not working

Im trying to first, check if both fields are not empty. if empty, alert user its empty. Then check if both user and password math and if they do match, then alert('welcome'). but if I type anything in the boxes, it passes and says welcome? Help!
const container = document.querySelector('.container');
const userInput = document.querySelector('#username');
const passInput = document.querySelector('#password');
const button = document.querySelector('button');
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
}
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
alert('password or username inavlid')
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
}
})*
Remove * at the end of your code and put ;
This:
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
evaluates the ! first. It's like:
if ((!userInput.value) == 'user21' || (!passInput.value) == 'user21') {
which of course won't result in the comparison you want.
Check if the username and password match, and if they don't, just have a plain else, without an else if there.
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
} else {
alert('password or username inavlid')
}
})
Also consider
using a proper modal instead of alert
if this is something you want any sort of reasonable security for, validate the logins using a backend database instead of hard-coding it on the front-end (which is trivially bypassable)

How to validate login trough post request upon clicking the login button in javascript?

I'm having problems getting this code to validate when clicking on the login button.
** my html code **
<form action="abc.php"
method="post"
onsubmit="return jcheck();">
<div id="id_box">
<input type="text"
name="email"
id="id_text" placeholder="E-mail" >
<div id="pass_box">
<input type="password"
name="password" id="pass_text" placeholder="Password">
<div id="submit_box">
<input
type="submit"
id="sub_box"
onClick="click_event()"
value="Login">
my javascript code:
function click_event(){
jcheck();
function validate_ID(){
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
if (filter.test(email.value)==false
&& filter1.test(email.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else
return true;
}
function validate_Pass() {
var pass =document.getElementById('pass_text');
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). 4,}$/;
if (filter.test(pass.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else
return true;
}
function jcheck();
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length == 0) && (pas.length == 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");$("#p_asterics").html("*"); }
else if (name.length == 0)) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if ((pas.length == 0)) {
if(name.length != 0)
{
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
$("#p_asterics").html("*");
$('#warn_pass').html("Password Required");
}
}
return false;
}
For starters you should always indent your code so errors are easier to find. I helped you do a bit of indenting and there are a lot of problems in the code. One thing you are doing wrong is you need to close functions, else branches and html tags.
All HTML tags should end with an end tag or be closed immediately.
Example <div></div> or <div /> if you don't do this the browser may render your page differently on different browsers. You have missed this on your input tags you divs and your form tag. Perhaps you should check the whole html document for more of these errors.
Functions should in javascript should always look like this
function name(parameters, ...) {
}
or like this
var name = function(parameters, ...) {
}
the the name and parameters may vary but generally the function should look like this.
if statements else branches and else if branches should all have enclosing brackets for their code.
if () {
//code
} else if () {
//code
} else {
//code
}
If you do not close start and close else brackets the javascript will behave in very strange and unexpected ways. In fact i think your code might not even compile.
If you are using chrome please press Ctrl + Shift + J and look in the Console tab. You should see some error messages there. When you click the submit button.
Also using onClick on the submit button may be dangerous as I don't think this blocks submit. A better way to achieve the requested functionality is probably to either use a button type input and go with onClick or use the onSubmit function on the form. You are currently using both and its really no way to tell if click_event or jcheck will run first. Perhaps you should debug and see in which order the function calls happen. You can use chrome to debug by pressing CTRL + Shift + J and setting debug points in the Source tab.
You have a minor stylistic error as well where you compare the result of the regexp test() with false. The return value of test is already a Boolean and does not need to be compared.
Here is a guestimation of how the HTML should look. Its hard to say if its right as I have no more info to go on than your code and it has a lot of problems.
<form action="abc.php" method="post" onsubmit="return jcheck();">
<div id="id_box">
<input type="text" name="email" id="id_text" placeholder="E-mail" />
</div>
<div id="pass_box">
<input type="password" name="password" id="pass_text" placeholder="Password">
</div>
<div id="submit_box">
<input
type="submit"
id="sub_box"
value="Login" />
</div>
</form>
Here is what the js might look like. Here the missing brackets makes it difficult to tell where functions should end so I have had to guess a lot.
/* I find it hard to belive you wanted to encapsule your functions inside the
click_event function so I took the liberty of placing all
functions in the glonbal scope as this is probably what you inteneded.
I removed the click_event handler as it only does the same thing as the onSubmit.
*/
function validate_ID() {
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
// Or feels better here as there is no way the email ends with bot #intellocut and #threadsol
// It also feels strange that these are the invalid adresses maby you messed up here and should change
// the contents of the else and the if branch.
if (filter.test(email.value) || filter1.test(email.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else {
return true;
}
}
// This funcion is not used Im guessing you should have used it in
function validate_Pass() {
var pass =document.getElementById('pass_text');
/* The filter below could cause problems for users in deciding password unless
you tell them some where what the rules are.
It was missing a { bracket before the 4 at the end that I added make sure
it is right now. If you are going to use the code.
*/
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). {4,}$/;
if (filter.test(pass.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else {
return true;
}
}
/* There are betterways to deal with multiple validation than chaining them like
this but Im guessing this will work. Im guessing that if you want to use the
password validation you should call it some where in this function.
like so 'validate_Pass()'
*/
function jcheck() {
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length === 0) && (pas.length === 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");
$("#p_asterics").html("*"); }
else if (name.length === 0) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if (pas.length === 0) {
if(name.length !== 0) {
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
}
}

tinyMCE jQuery form validation

I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});

JQuery Validation for Two Password Fields

Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
    $(".error").show(500);
}else{
 $(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.

return false in if statement not recognized in IE - Jquery

The following code checks to see if user entered their email address & password.
This works great in Firefox/Chrome, but I'm having issues in IE. In IE, when you don't enter your user name and password, it turns the boxes red (as expected), and also doesn't change the text to 'Loading...', so it goes to the return false in the last else statement, but IE doesn't recognize it for some reason—is there a work around I should know about?
$('#gettheiremail').submit( function() {
var passwordinfo = $('#passwordtextbox').val();
if ($('#signuptextbox').attr('value') == '' || $('#signuptextbox').attr('value') == 'Your Email Address' ) {
$('#signuptextbox').css('color','red');
$('#signuptextbox').css('border','3px solid #ff0000');
}
if ($('#passwordtextbox').attr('value') == '') {
$('#fakepassword').css('color','red');
$('#fakepassword').css('border','3px solid #ff0000');
$('#passwordtextbox').css('border','3px solid #ff00000');
}
if((!($('#signuptextbox').attr('value') == '' || $('#signuptextbox').attr('value') == 'Your Email Address' )) && $('#passwordtextbox').attr('value') != '' )
{
$('#sendform').val('Loading...');
}
else
{
return false;
}
});
Here's the working code after fixes
$('#gettheiremail').submit( function(e) {
var signuptextbox = $('#signuptextbox').attr('value');
if (signuptextbox == 'Your Email Address' ) {
$('#signuptextbox').css('color','red');
$('#signuptextbox').css('border','3px solid #ff0000');
e.preventDefault();
}
var passwordtextbox = $('#passwordtextbox').attr('value');
if (passwordtextbox == '' || passwordtextbox == 'Enter Your Email Password') {
$('#fakepassword').css('color','red');
$('#fakepassword').css('border','3px solid #ff0000');
$('#passwordtextbox').css('border','3px solid #ff00000');
e.preventDefault();
}
if(!((passwordtextbox == '' || passwordtextbox == 'Enter Your Email Password') && (signuptextbox == 'Your Email Address')))
{
$('#sendform').val('Loading...');
}
});
Have you tried:
$('#gettheiremail').submit(function(e) {
/* Other code */
e.preventDefault();
/* Other code */
});
If neither of the two things at the end of your code are happening, then the odds are that you're never reaching the end of that code — e.g., that an exception is being thrown in the middle. You'll want to walk through with a debugger (you can use the built-in stuff in IE8+, or VS.Net [there's a free edition] for earlier versions).
Off-topic: You're reiterating a lot of lookups:
if ($('#signuptextbox').attr('value') == '' || $('#signuptextbox').attr('value') == ' ...
Every time you write $('#xyz') it triggers several function calls, at least one memory allocation, and causes a DOM lookup (which is not necessarily all that fast, even when looking up by id). Similarly, constantly calling attr again for the same attribute is more unnecessary overhead (though not nearly so much). Instead:
var signuptextbox = $('#signuptextbox'),
signupvalue = signupvalue = signuptextbox.attr('value');
if (signupvalue == '' || signupvalue == '...
(Or don't keep the signuptextbox if you just need its value.)

Categories