Jquery keypress to validate email inputs - javascript

What I'd like to accomplish is this:
If a user types in a valid email, display the (.check)'ok' sign. If not valid, display nothing(for the time being. I'll put something in later).
I have 3 email fields. I'm trying to 'validate' for each one.
<form id="emailsForm" method="POST" action="/account/recommend/">
<div class="prepend">
<p><strong>Emails:</strong></p>
<div>
<span class="added"><p class="check">ok</p></span>
<input type="email" id="email1" class="input-text" onblur="alert(/([A-Z0-9a-z_-][^#])+?#[^$#<>?]+?\.[\w]{2,4}/.test(this.value))">
</div>
<div>
<span class="added"><p class="check">ok</p></span>
<input type="email" id="email2" class="input-text">
</div>
<div>
<span class="added"><p class="check">ok</p></span>
<input type="email" id="email3" class="input-text">
</div>
<button type="submit" class="submit">Send</button>
</div>
</form>
$("form#emailsForm :input").each(function(){
$('input').blur(function() {
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test(this.value)){
$('input').siblings(".check").css('visibility', 'visible');
}
else {
}
});
});
http://jsfiddle.net/RFcaN/23/ What am I doing wrong?
Thanks for your help and suggestions!

First off you need to find the sibling of this input, so change your selector from $('input') to $(this).
Secondly, .check is not a sibling of the input. It's a descendant of the sibling.
$(this).siblings(".added").find('.check').css('visibility', 'visible');

Related

Struggling to validate the email when toggling

The HTML Code:
<div class="form-container">
<form method="post" id="email">
<div class="form-group">
<label for="exampleInputEmail1" class="typingA spacing"><i class="bi bi-envelope"></i> Email Address:</label>
<input type="email" class="form-control" id="typingEmail" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</form>
<form method="post" id="subject">
<fieldset class="form-group">
<label for="subject" class="typingA spacing">Subject:</label>
<input type="text" class="form-control"name="subject"placeholder="Subject" >
</fieldset>
</form>
<form method="post" id="content">
<fieldset class="form-group">
<label for="content" class="typingA spacing">What would you like me to ask?</label>
<textarea class="form-control" name="content" rows="3" placeholder="What would you like me to ask, Sir/Madam?"></textarea>
</fieldset>
</form>
<div id="buttons">
<button type="submit" id="next" class="btn btn-primary" enabled='enabled'>Next</button>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</div>
The JQuery part:
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#buttons").click(function() {
$("#next").click(function() {
if(isEmail($('#typingEmail').val()) == false)
{
$(':input[type="submit"]').prop('disabled', false);
}
$("#subject").toggle();
$("#email").toggle();
$("#next").click(function() {
$("#content").toggle();
$("#email").toggle();
$('#next').attr('disabled', true);
});
});
});
What I am trying to do is validate the email. if it is valid, the "next button" should enable, else it should not enable. I tried but didn't succeed. I appreciate your time and help. Ta!
Note I tried to find similar topic on StackOverflow but didn't find it. So, just a humble
request, dont report.
I think you just want to disable and enable the next button when the email is valid or not valid, here is a workaround, i don't know whether it cover your requirement or not.
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$(function(){
var $emailInput = $('#typingEmail');
var $nextBtn = $('#next');
function checkIfEmailOk(){
return isEmail($emailInput.val());
}
function toggleNextByEmail(){
$nextBtn.prop('disabled', !checkIfEmailOk());
}
// or you can listen the 'blur' event
// but the validation will only triggered after your cursor moved out from the input area
// and the 'input' event may need some polyfill in lower versions of IE
$emailInput.on('input', function(){
toggleNextByEmail();
});
// disable the next button's onclick event when the email is not valid
$nextBtn.on('click', function(e){
if(!checkIfEmailOk()){
// email not ok
e.preventDefault();
$emailInput.focus();
}
});
// if you want to check the email input and toggle the next button when domready
toggleNextByEmail();
});
You can try it in the codepen.

HTML5 validation does not trigger when fields are not accesible

I have a form with multiple fields, and I need to scroll 10-15 fields until the submit button. I want to check if the form is valid or not via jquery. If the first field of my form is required and I click on the submit button the field borders are going red but the message is not displayed. If I remove all the required fields from the top and just add the last fields as required the message is displayed. If I resize the browser to be able to see the first field when press the submit the validation message is displayed. Does this function (reportValidity) work with not accessible fields?
$('form').each(function() {
var $form = $(this);
$form.find(':submit').on({
'mousedown': function(e) {
var form = $(this).closest('form')[0];
if (form.checkValidity()) {} else {
form.reportValidity();
}
},
});
});
.test {
margin-bottom: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<input type=submit>
</form>
It can be solved by adding event.preventDefault() before the reportValidity() call.

how to do html form vaildation in jquery

i am using html and jquery to do some form vaildations
for ex if user click on a field and doesn't enter any thing, than he clicks on different field... i want to turn field border to red. this way user will know that he can not skip this field...
also when user clicks on button submit, than i also want to do this same, if field is empty than turn border to red
below is what i have so far, is there a better way to do this? bbc it seem like i am repeating alot of same code
on up side it does work fine, so guess i can just keep on repeating code
note i have like 20+ fields so jquery function will be long
forgot to tell that i am using asp fields:
<asp:TextBox ID="FirstNameCTB" ClientIDMode="Static" class="input form-control input-md" runat="server"></asp:TextBox>
javascript code:
<script type="text/javascript">
$(function () {
$('#FirstNameCTB').blur('input', function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '')
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
});
$('#LastNameCTB').blur('input', function () {
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '')
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
});
$('.CHECKOUTLBC').click(function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '') {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
}
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '') {
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
}
});
});
</script>
https://jqueryvalidation.org/ can be your solution.
Also here's the examples.
https://jqueryvalidation.org/files/demo/
This plugin has, red border, submit control etc.
Also this plugin will be good.
http://www.formvalidator.net/#reg-form
$.validate({
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
// Restrict presentation length
$('#presentation').restrictLength( $('#pres-max-length') );
<form action="" id="registration-form">
<p>
E-mail
<input name="email" data-validation="email">
</p>
<p>
User name
<input name="user" data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
</p>
<p>
Password
<input name="pass_confirmation" data-validation="strength"
data-validation-strength="2">
</p>
<p>
Repeat password
<input name="pass" data-validation="confirmation">
</p>
<p>
Birth date
<input name="birth" data-validation="birthdate"
data-validation-help="yyyy-mm-dd">
</p>
<p>
Country
<input name="country" id="country" data-validation="country">
</p>
<p>
Profile image
<input name="image" type="file" data-validation="mime size required"
data-validation-allowing="jpg, png"
data-validation-max-size="300kb"
data-validation-error-msg-required="No image selected">
</p>
<p>
User Presentation (<span id="pres-max-length">100</span> characters left)
<textarea name="presentation" id="presentation"></textarea>
</p>
<p>
<input type="checkbox" data-validation="required"
data-validation-error-msg="You have to agree to our terms">
I agree to the terms of service
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
Assuming all your form inputs are called input, you could loop through them and apply the function with something similar to this.
var inputs = document.getElementsByTagName('input');
for(n = 0; n < inputs.length; n++){
$(function () {
inputs[n].blur('input', function () {
if (inputs[n].val().trim() == '')
inputs[n].css('border-color', 'red');
else
inputs[n].css('border-color', '');
});
});
}
couple things:
issue maybe be that javascript is beeing run before the controls
you should not mix core javascript with jquery libary
you do not need loop when using blur, on, click, etc jquery functions
keeping all those above things in mind, below is a better solutions. works for me
$(function () {
$(".input").blur(function () {
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
Have a look at this example below.
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>
Have a look at this example:

Additional input fields when filling up previous

Im trying to add additional fields in case when my user has filled up one group of inputs. So the idea is that when he finishes filling up the last input in that group, another group of inputs for same kind of items collapses/appears under existing one. One group of items consists of three inputs. After filling up that one, another group of inputs would appear under. I will present my code under. Hope someone can help me!
<div class="new-providers">
<div class="provider-append" id="toggleExtraProvider">
<div class="form-group">
<label>Provider</label>
<input type="text" class="form-control" id="practiceProvider" placeholder="Full provider name with coredentials" />
</div>
<div class="form-group">
<label>NPI</label>
<input type="text" class="form-control" id="providerNPI" placeholder=" NPI" />
</div>
<div class="form-group">
<label>MM #</label>
<input type="text" class="form-control" id="providerM" placeholder="M Provider #" />
</div>
<hr />
</div>
</div>
I tried appending the provider-append class on to the new-providers class
This is my jQuery script:
<script type="text/javascript">
$(document).ready(function() {
$("#toggleExtraProvider div.form-group input").each(function() {
if($(this).val() =! "") {
var target = $("new-providers");
target.append(".provider-append");
}
});
});​
</script>
You need to check for empty input box in a particular div use filter() for that
and use jQuery clone() to clone the parent div (input group) if all input box filled. And you should use change event instead of input, Since input will be overkill here it will run each time when you change a single character in text box on the other hand change event fires when user finish typing and input box loose focus.
$(document).ready(function () {
$(document).on("change",".provider-append input",function(){
var allHaveText;
var parentDiv = $(this).closest("div.provider-append");
emptyInputs=parentDiv.find("input[type=text]").filter(function () {
return !this.value;
});
if(emptyInputs.length==0)
{
newGroup = parentDiv.clone().appendTo(".new-providers");
newGroup.find("input[type=text]").each(function(){
$(this).val("");
});
}
});
});
Here is a working sample
$(document).ready(function () {
$(document).on("change",".provider-append input",function(){
var allHaveText;
var parentDiv = $(this).closest("div.provider-append");
emptyInputs=parentDiv.find("input[type=text]").filter(function () {
return !this.value;
});
if(emptyInputs.length==0)
{
newGroup = parentDiv.clone().appendTo(".new-providers");
newGroup.find("input[type=text]").each(function(){
$(this).val("");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="new-providers">
<div class="provider-append">
<div class="form-group">
<label>Provider</label>
<input type="text" class="form-control" placeholder="Full provider name with coredentials" />
</div>
<div class="form-group">
<label>NPI</label>
<input type="text" class="form-control" placeholder=" NPI" />
</div>
<div class="form-group">
<label>MM #</label>
<input type="text" class="form-control" placeholder="M Provider #" />
</div>
<hr />
</div>
</div>
I hope it will help you.

jQuery: Validating fields before submitting (multistep form)

I have a form which consists of 2 steps. What I'd like to do is validate each step before continuing to the next; the user should not be able to get to step 2 of step 1's fields are invalid.
js fiddle: http://jsfiddle.net/Egyhc/
Below you can find the simplified version of the form:
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
Continue to step 2
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
​
$(function() {
$('#step1_btn').click(function() {
$('#step1').hide();
$('#step2, #submit_btn').show();
});
});​
How do you guys suggest I achieve this?
There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. So you can handle the show/hide logic of your steps and for validation you could just do this:
As this suggests: ignore hidden
$("form").validate({
ignore: ":hidden"
});
If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid().
I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/>
See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/

Categories

Resources