How to add another statement on keypress on email validation with jQuery - javascript

Validations is working fine, if valid email is entered, displays a hidden box if not valid is showing a message error on a overlay, but how to check if keydown or return? any ideas guys?
This is my code, which can also be accessed in a jsFiddle:
function validateEmail() {
var validEmail = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
$('#user_email').blur(function(){
if (validEmail.test(this.value)) {
$('.masked-check').fadeIn(300)
}
else {
$('.masked-check').fadeOut(300);
$('.overlay').append('<div class="alert alert-error" id="errors"></div>');
showOverlay($('#errors').html('Please enter a valid email...'));
}
});
}
validateEmail();
I not sure if this is the way to do it but works for me now, the only issue is not listening to a keypress keyup or keydown. Here is the updated http://jsfiddle.net/creativestudio/bKT9W/3/ I am not sure is this is the best way to do it but works for now.
function validateEmail() {
var validEmail = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
$('#user_email').blur(function(){
$('.masked-check').hide();
if (validEmail.test(this.value)) {
$('.masked-check').fadeIn(300)
}
else {
$('.masked-check').fadeOut(300);
$('.overlay').append('<div class="alert alert-error" id="errors"></div>');
showOverlay($('#errors').html('Please enter a valid email...'));
}
if ($('#user_email').val()=='') {
$('.masked-check').hide()
}
});
}
validateEmail();

I like the idea of fade in/out based on valid/invalid input.
I played around a bit and following seem to be working for me ok: http://jsfiddle.net/yc9Pj/
function validateEmail(){
var validEmail = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
$('#user_email').keyup(function(){
if (validEmail.test(this.value)) {
$('.masked-check').fadeIn(300)
}
else {
$('.masked-check').fadeOut(300);
//alert('Please enter a valid email');
}
});
}
validateEmail();​
please note, that I adapted regex for email based on this reply: Using a regular expression to validate an email address
Moreover keyup worked best for me, as keypress didn't handle backspace (solution found here: jQuery: keyPress Backspace won't fire?)

I believe what you're trying to achieve is for the email validation to run after each key-stroke and to keep notifying the user if their email was valid or not until it is valid.
There is a jQuery .keypress() event to identify a keypress event.
I got this working here:
http://jsfiddle.net/bKT9W/2/
EDIT: I believe Peter's answer below is much better: https://stackoverflow.com/a/13298005/1415352
He suggests a better regex and also the .keyup() event which solves the backspace issue which arises when using .keypress()

Change your function "validateEmail" to the following:
function validateEmail(){
var validEmail = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
$('#user_email').keydown(function(event){
if (event.keyCode !== 13) {
return;
}
if (validEmail.test(this.value)) {
$('.masked-check').fadeIn(300)
}
else {
//$('.masked-check').fadeOut(300);
alert('Please enter a valid email');
}
});
}

Related

jQuery Form Validation -- Correct Submission Not Clearing Errors

Working on form validation in jQuery. All of my validations seem to be working correctly.
See JSFiddle here.
If you submit the form with no data, all of the correct errors appear.
If you fix one of the fields, the error message for that field does not clear.
I think it probably is something wrong with my logic, but unsure if there is an easy way to try and check the validation again?
My code for submit in jQuery is here. The first four validate functions are checking for errors and displaying errors if there are any. If there are any errors with anything, the form is prevented from submitting. If there is no error, an alert is displayed and the submission is allowed. I know that the problem is that after that first if statement finds an error - there is no way to look and see if the error is fixed and to clear that error. So I'm stumped on where to go with this - would it be better off in a loop maybe?
// On Form Submission Validate Form
$("#contact_submit button").click(function(event){
error_name = validateName();
error_email = validateEmail();
error_activity = validateActivities();
isCreditIssue = validateCredit();
event.preventDefault();
var valid = true;
if ((error_name) || (error_email) || (error_activity) || (isCreditIssue)){
console.log("errors");
valid = false;
} else {
alert('GREAT! form completed');
valid = true;
}
if (valid) {
return;
}
You left out hide statements when the form values become valid at many places. Just an example (inside validateZip):
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
errorZip = false;
}
You should replace it with this:
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
$(".error_zip").hide();
errorZip = false;
}

HTML - Javascript - input condition

Ive been looking but cant seem to find much clarification...
I am creating a form -
If a user is to select an option for contact "email",
the user must enter a text value for email input type.
Here is a fiddle- https://jsfiddle.net/4s3bLf65/
if ($("input[name='option']").val()=='email') &&($("input[name='email1']").val() == '')
{
alert('Enter email');
return false;
}
I cant seem to figure out the proper syntax for the js...
Any suggestions?
Try that way:
if ($("input[name='option']:checked").val()=='email' && $("input[name='email1']").val() == '')
{
alert('Enter email');
return false;
}
Add your code to a click handler or submit handler so it executes when the button is pressed.
Your if had too many perentheses
You were not getting the value of the :checked box.
$(document).ready(function() {
$('input[name="btn_submit"]').click(function() {
if ($("input[name='option']:checked").val() == 'email' && $("input[name='email1']").val() == '') {
alert('Enter email');
return false;
}
});
});
Fiddle: https://jsfiddle.net/ojqa46a0/

Password verification using javascript and jquery

I am doing password verification. I enter the password and then i re enter the password. But at every key press it gives me a tick mark sign which I dont want and also, even if I enter a wrong password it doesn't go the else part which gives the delete image. Can someone help me out. I am new at this.
function checkPasswordMatch() {
var password = $("#password").val();
var confirmPassword = $("#verifyPassword").val();
if (password != confirmPassword)
{
$("#marker").prepend('<img src="https://cdn3.iconfinder.com/data/icons/freeapplication/png/24x24/Apply.png" />');
}
else
{
$("#marker").prepend('<img src="https://cdn3.iconfinder.com/data/icons/musthave/16/Delete.png" />');
}
}
$(document).ready(function () {
$("#verifyPassword").keyup(checkPasswordMatch);
});
There are 2 problems with your approach.
First, to prevent the function to run at every keypress use the change event instead of keyup.
Second, I think you inverted the statement in the if, use == instead of !=
function checkPasswordMatch() {
var password = $("#password").val();
var confirmPassword = $("#verifyPassword").val();
if (password == confirmPassword){
$("#marker").html('<img src="https://cdn3.iconfinder.com/data/icons/freeapplication/png/24x24/Apply.png" />');
}else{
$("#marker").html('<img src="https://cdn3.iconfinder.com/data/icons/musthave/16/Delete.png" />');
}
}
$(document).ready(function () {
$(document).on('keyup','#verifyPassword', checkPasswordMatch );
});
edit: changed back the keyup event to match the request
To prevent this of happening each time you type somthing, you should change your event. I advise you to use the change event, at the passwords fields. See:
$(document).ready(function () {
$(document).on('change','#password, #verifyPassword', checkPasswordMatch );
});

Prevent textarea with only <br> from submitting

I am trying to build a comment section that allows instant preview on the front end.
Everything worked fine except the behavior after submitting the comment.
In my code, I trigger the submission of the comment when the user press the Enter key in the textarea, then clear the textarea by resetting the value.
However, even after I disabled the default behavior of the enter key by declaring e.preventDefault(), a new line is still inserted when enter is pressed repeatedly.
Also, even after I check the length of the value of the textarea before submitting, my code accept comment with only / '\n' as valid content and hence the user will be able to submit 'empty' comment if they press enter in the textarea multiple times...
Please help, I cannot think of a solution and I am considering to add a post button where the user has to manually click it to submit...
My code on fiddle:
http://jsfiddle.net/8ve0gLab/2/
My code:
$(document).ready(function(){
$('#comment-input').keydown(function(e){
var commentContent = $(this).val()
if (e.which == 13) {e.preventDefault()}
if (e.which == 13) {
e.preventDefault()
if (commentContent.length != 0) {
$('#comment').append(commentContent)
$(this).val('')
}
else {
alert('Comment is empty')} /*This line is not working properly*/
}
})
})
Try change your code to
$(document).ready(function(){
$('#comment-input').keydown(function(e){
var commentContent = $(this).val();
if (e.which == 13) {
if (commentContent.trim()){
$('#container').append("<p>"+commentContent+"</p>");
$(this).val('');
}
else {alert('Area is empty');}
}
})
})
notice the ".trim()" which is a javascript string method.
you can try in the jsfiddle here : http://jsfiddle.net/xdxqwLof/
This may address your issue:
if (event.keyCode == 10 || event.keyCode == 13){
event.preventDefault();
}
JS Fiddle Demo

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

Categories

Resources