I'm trying to validate email upon submit. Right now, I have it working so that it validates if I tab from the email to submit button, and also if I click the submit button directly. However, it doesn't validate if I press Enter from within the email field. Also, once it validates on clicking submit, I have to click the button again to actually submit.
The reason is because I start with type="button" rather than type="submit" on the submit input. This is because before when I started with type="submit" it would submit regardless of whether the email was valid or not.
So now, I start with type="button", validate the email, and then change it to type="submit" on valid emails. However, like I mentioned, it still isn't the most user-friendly (even though it does work as is). I'd like to add the user-friendly features described above. Here is the code I have (note: I'm using the Mailgun jQuery email validator for the validation part):
<form accept-charset="UTF-8" id="icpsignup" name="icpsignup" action="process.php" method="post">
<p>
<input type="text" onfocus="this.value=''" onblur="this.value=!this.value?'Enter name...':this.value;" class="txtbox_index" placeholder="Enter name..." value="Enter name..." name="fields_fname" id="fields_fname">
</p>
<p>
<input type="text" class="txtbox_index" onfocus="this.value=''" onblur="this.value=!this.value?'Enter email...':this.value;" name="fields_email" id="fields_email" Value="Enter email..." placeholder="Enter email...">
<input type="text" style="border: none;color: #fff;cursor: none; background-color:transparent; height:0px;" size="1" value="<?=$country_field;?>" name="fields_country" id="fields_country">
</p>
<div id="status"></div>
<p class="forfree">
<input type="button" value="Signup For Free!" id="validate_submit" class="signupbtn_new" name="submit">
</p>
<input type="hidden" value="<?php echo $paramstring ;?>" name="fields_trk">
</form>
<script src="js/vendor/jquery.js"></script>
<script src="js/mailgun_validator.js"></script>
<script>
// document ready
$(function() {
// capture all enter and do nothing
/* $('#fields_email').keypress(function(e) {
if(e.which == 13) {
$('#fields_email').trigger('focusout');
return false;
}
});
// capture clicks on validate and do nothing
/* $("#validate_submit").click(function() {
return false;
});*/
// attach jquery plugin to validate address
$('#fields_email').mailgun_validator({
api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
in_progress: validation_in_progress,
success: validation_success,
error: validation_error,
});
});
// while the lookup is performing
function validation_in_progress() {
$('#status').html("<img src='images/loading.gif' height='16'/>");
}
// if email successfull validated
function validation_success(data) {
$('#status').html(get_suggestion_str(data['is_valid'], data['did_you_mean']));
}
// if email is invalid
function validation_error(error_message) {
$('#status').html(error_message);
}
// suggest a valid email
submitHandler: function(form) {
function get_suggestion_str(is_valid, alternate) {
if (alternate) {
form.preventDefault();
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else if (is_valid) {
form.submit();
//return '<span class="success">Address is valid.</span>';
} else {
form.preventDefault();
return '<span class="error">Address is invalid.</span>';
}
}
}
// Another version of trying to using the Submithandler. I'm not sure if I'm supposed to use the validate or not.:
$(function() {
$("#icpsignup").validate({
submitHandler: function('icpsignup') {
function get_suggestion_str(is_valid, alternate) {
if (alternate) {
icpsignup.preventDefault();
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else if (is_valid) {
icpsignup.submit();
//return '<span class="success">Address is valid.</span>';
} else {
icpsignup.preventDefault();
return '<span class="error">Address is invalid.</span>';
}
}}
})
})
</script>
UPDATE: A MORE complete answer:
NOTE: this assumes you will be using jQuery 1.4.3 or higher
The SUBMIT event is sent to an element when the user is attempting to submit a FORM:
It can only be attached to <form> elements.
Forms can be submitted either by clicking an explicit:
<input type="submit">,
<input type="image">, or
<button type="submit">,
or
by pressing Enter when certain form elements have focus.
NOTE: *Depending on the browser, Enter may only cause a form submission if:
the form has exactly one text field, or
only when there is a submit button present.
Therefore, your code shouldn't rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key which is character code 13.
Here is information about how to use the .keypress() handler from jQuery.com
Here is a chart comparing all ASCII character/key codes, HTML escape codes, and they keys/character they represent.
You can get more detailed information at the jQuery.com site .submit() page HERE.
In your scenario (and most), I would use a <input type="submit"> button and capture the SUBMIT event.
In the submit handler callback function:
$( "form#icpsignup" ).submit(function( evt ){
//...
$('#fields_email').mailgun_validator({
api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
in_progress: validation_in_progress,
success: validation_success,
error: validation_error,
});
//...
}
You will need to validate your <form> (i.e. use whatever code, statement, etc. on one or more input fields). Then upon...
success - use a return true statement
failure - use an evt.preventDefault(); where evt is the argument passed to your submit handler.
.
Below is a detailed example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>submit demo</title>
<style>
p {
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'correct' to validate.</p>
<form action="javascript:alert('success!');"
<div>
<input type="text">
<input type="submit">
</div>
</form>
<script>
// "function( evt )" is an anonymous function. It *is* your handler
$( "form" ).submit(function( evt ) { // evt is the *event* object.
// name it whatever you'd like.
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return true;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
evt.preventDefault();
});
</script>
</body>
</html>
Related
I need to find a way to tell if a field is empty, using javascript or html, here's the code:
<script>
function setAction(form) {
alert(form.name);
return false;
}
</script>
A Snippet like this should do the trick, putting inputx as the selected field your testing for
if (inputtx.value.length == 0){
alert("empty form");
return false;
} else
alert("filled form");
return true;
}
The alerts are just to let you know if its working, you could also use a
console.log("empty/filled form");
and then check in the web browser console
Your code snippet is so generic, but is not a problem. For solving this task you will need to get HTML input object in JavaScript and extract it's value length to compare if is greater than zero. Notice that you are not able to get HTML object if the window is not fully loaded this is why you will need to deal with DOM events.
Creating the form:
<form id="myForm" onSubmit="return false;">
<label for="name">First name:</label><br>
<input type="text" id="nameField" name="name" value="Your Name"><br>
</form>
In this example I selected enter key and will be used to check if the form field is empty or not, this is why onSubmit="return false;" event was bound to return false, avoiding reloading the page on form submit with enter key press.
Creating script part
window.onload = function windowLoaded(windowEvent)
{
const myInputFieldHtmlObject = document.querySelector("#nameField");
myInputFieldHtmlObject.onkeypress = function(event)
{
if(event.which == 13)
{
if(myInputFieldHtmlObject.value.length == 0)
{
alert("Fill please the name field.");
}
}
}
myInputFieldHtmlObject.onfocus = function(event)
{
myInputFieldHtmlObject.value = "";
}
}
Bind onload event to the window object. This guarantee that all HTML objects in the page are loaded before accessing it with document.querySelector("#nameField").
Bind on key press and on focus events to your each individual fields in the form what need checks. On key press will check after you type the name and press Enter key (value 13) if number of characters are at least 1, otherwise will pop an error.
On focus event will just clear the text input default value to nothing.
Complete example:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>My Form Test</title>
<style>
html, body
{
width: 100%;
height: 100%;
margin: 0 !important;
padding: 0 !important;
overflow: hidden;
}
</style>
<script>
window.onload = function windowLoaded(windowEvent)
{
const myInputFieldHtmlObject = document.querySelector("#nameField");
myInputFieldHtmlObject.onkeypress = function(event)
{
if(event.which == 13)
{
if(myInputFieldHtmlObject.value.length == 0)
{
alert("Fill please the name field.");
}
}
}
myInputFieldHtmlObject.onfocus = function(event)
{
myInputFieldHtmlObject.value = "";
}
myInputFieldHtmlObject.onSubmit = function(event)
{
return false;
}
}
</script>
</head>
<body>
<h2>My Form</h2>
<form id="myForm" onSubmit="return false;">
<label for="name">First name:</label><br>
<input type="text" id="nameField" name="name" value="Your Name"><br>
</form>
</body>
</html>
If you have a single form and you want the index numbers of empty fields:
function emptyFields(form) {
return [...document.forms[form]].flatMap((field, index) =>
field.value.length < 1 ? [index] : []);
}
console.log(emptyFields('data'));
<form name='data'>
<input>
<input value='not empty'>
<input>
<input>
<input value='not empty'>
<input>
</form>
I have search field and it doesn't have that typical submit button. It looks like this:
HTML:
<div class="input-group">
<input type="text" class="form-control" name="keyword" id="searchbox" onkeypress="return checkLength()"/>
<span class="btn btn-primary input-group-addon" onclick="checkLength()"><i class="fa fa-search"></i></span>
</div>
I only added a span and not the input element for submit button. How do I validate if the user types or inputs not less than 2 characters? If the user types in 1 character only then presses that search button or just hit the enter key, there should be a red error message at the bottom of the search field saying "Keyword should be not less than 2 characters" or something like that.
I tried this code but it's not working:
function checkLength(){
var textbox = document.getElementById("searchbox");
if(textbox.value.length <= 10 && textbox.value.length >= 2){
alert("success");
} else {
alert("Keyword should be not less than 2 characters");
$(document).keypress(function (e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode && keyCode == 13) {
e.preventDefault();
return false;
}
});
}
}
Need help. Thanks.
EDIT:
After inputting keywords and hit the enter key, the page would redirect to a search results page, but that should be prevented from happening if the inputted keyword does not have 2 or more characters, hence, displaying a red text error message below the search field. How to do it?
You can use pattern attribute in HTML5 input, and you can validate the text with just CSS:
.error {
display: none;
font: italic medium sans-serif;
color: red;
}
input[pattern]:required:invalid ~ .error {
display: block;
}
<form>
<input type="text" name="pattern-input" pattern=".{2,}" title="Min 2 characters" required>
<input type="submit">
<span class="error">Enter at least two characters</span>
</form>
Here is the Fiddle
Note: This would work with all modern browsers, IE9 and earlier doesn't seems to have support for :invalid, :valid, and :required CSS pseudo-classes till now and Safari have only partial support.
Jquery Validation plugin can be used. it is very simple.
$(document).ready(function(){
$("#registerForm").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<form id='registerForm' name='registerForm' method='post' action='' > <p>
Search <input type='text' name='name' id='name' minlength="2" class='required' />
</p>
</form>
Ref :
http://jqueryvalidation.org/documentation/
Try utilizing .previousElementSibling to select span .nodeName to select input set div .innerHTML to empty string "" or "Keyword should be not less than 2 characters" , using input event
var msg = document.getElementById("msg");
function checkLength(elem) {
var el = elem.type === "text" ? elem : elem.previousElementSibling
, len = el.value.length < 2;
msg.innerHTML = len ? "Keyword should be not less than 2 characters" : "";
$(el).one("input", function() {
checkLength(this)
})
}
#msg {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-group">
<form>
<input type="text" class="form-control" name="keyword" id="searchbox" />
<input type="button" class="btn btn-primary input-group-addon" onclick="checkLength(this)" value="X" />
<div id="msg"></div>
</form>
</div>
I made a jsfiddle that might be close to what you want.
Take a gander and see what you can make of it.
Don't hesitate to ask questions about it.
My best explanation is:
There is an event handler on both the input and the submit button that test the input's value. Based on the conditions that I have assumed from your question, either a success alert or an error message is shown. The success alert could be replaced with an ajax call or to trigger a form submission.
I have a problem that others seem to have, but I cannot get the recommended solution (i.e., "return false;") to work. Any help would be great!
Description:
When the form is submitted, I want to validate the input is in the correct format (i.e., type="email") and launch an alert (i.e., "Form submitted.") without the page refreshing. Currently, the alert does not appear and the page refreshes.
Test Code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- JavaScript -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<!-- Form -->
<form>
<input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
<button type="submit" id="submit">Submit</button>
</form>
<!-- Alert on Submission -->
<script>
console.log("Ready to Go!");
$('#submit').submit(function () {
alert("Form submitted.");
return false;
});
</script>
</body>
</html>
You will want to catch the submit event of the form. There is no submit event on a button.
$('form').submit(function () {
if (*everything ok*) {
alert("Form submitted.");
} else {
return false;
}
});
Ideally you would help identify your <form>, either with an ID or a class, i.e.:
<form id="xyz-form">
And then change your selector to:
$('#xyz-form').submit(...);
Now this is only to stop the form from submitting when there are errors. When return false; isn't the path the submit callback takes, your page is going to refresh. If you want to submit the data to the server without a refresh, you will need to approach this differently.
Give your form an ID, and change your jquery to use #formid instead.
For example :
<form id="form">
<input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
<button type="submit" id="submit">Submit</button>
</form>
<script type="text/javascript">
$('#form').submit(function () {
alert("Form submitted.");
return false;
});
</script>
The event handler attached to the submit function in jQuery can be the form element or a div element. Read more on jQuery API
You can implement a click event when the user clicks on the submit button without its default submitting behavior with jQuery's preventDefault function
console.log("Ready to Go!");
$('form').submit(function () {
alert("Form submitted.");
return false;
});
$("#submit").click(function(e){
if (hasError){
e.preventDefault();
}
else{
alert("success");
}
})
The if and else statements are created for simple validation. For the scope of your question, I leave most of the coding for your creativity. But you can basically create a simple function to check for errors with the user inputs, if there are errors,prevent the submit button's default submission behavior. If the inputs are not empty and if inputs are free of errors, alert the user that the form has been submitted.
try this instead
$('#submit').click(function () {
alert("Form submitted.");
return false;
});
it'll accomplish what you want.
basically the click fires before the submit
try this snippet to clear things up
console.log("Ready to Go!");
$('#submit').click(function () {
alert("Form submitted.");
//return false;
return true;
});
$("form").submit(function( event ) {
alert("woot woot");
});
I have the following problem:
2 forms that need to be submitted with one button. I will explain how it should work.
And of course my code so far.
#frmOne contains a url field where I need to copy the data from to my #frmTwo, this works.
(it forces the visitor to use www. and not http:// etc)
When I press 1 submit button
Verify fields #frmOne (only url works now, help needed on the others)
Call #frmTwo and show result in iframe. result shows progress bar (works)
But Div, modal or any other solution besides iframe are welcome.
Close #frmOne (does not work)
Finally process (submit) #frmOne if #frmTwo is done (does not work)
Process completed code of #frmTwo in iframe =
<div style='width' id='information'>Process completed</div>
<ol class="forms">
<iframe width="100%" height="50" name="formprogress" frameborder="0" scrolling="no" allowtransparency="true"></iframe>
<div id="txtMessage"></div>
</ol>
<div id="hide-on-submit">
<form id="frmOne" method="post">
<input type="text" name="company" id="company" >
<input type="text" name="url" id="url" >
<input type="text" name="phone" id="phone" >
<input type="text" name="occupation" id="occupation" >
<textarea rows="20" cols="30" name="summary" id="summary" >
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
<form id="frmTwo" method="post" target="formprogress"></form>
<script>
jQuery(document).ready(function(){
//Cache variables
var $frmOne = $('#frmOne'),
$frmTwo = $('#frmTwo'),
$txtMessage = $('#txtMessage'),
frmTwoAction = 'http://www.mydomainname.com/form.php?url=';
//Form 1 sumbit event
$frmOne.on('submit', function(event){
event.preventDefault();
var strUrl = $frmOne.find('#url').val();
//validation
if(strUrl === ''){
$txtMessage.html('<b>Missing Information: </b> Please enter a URL.');
}
else if(strUrl.substring(0,7) === 'http://'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>http://</b> is not supported!');
}
else if(strUrl.substring(0,4) !== 'www.'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>Invalid URL</b> Please enter a valid URL!');
}
else{
//set form action and submit form
$frmTwo.attr('action', frmTwoAction + strUrl).submit();
$('#hide-on-submit').hide(0).fadeIn(1000);
$('form#frmOne').submit(function(e) {
$(this).hide(1000);
return true; // let form one submit now!
}
return false;
});
});
</script>
read here https://api.jquery.com/jQuery.ajax/. basically you need to submit the first one with $.ajax and then, when you get the server response (in the success() function ) you need to send the second form, again width ajax().
Something like:
$form1.on('submit', function(e) {
e.preventDefault(); //don't send the form yet
$.ajax(
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize()
).success(function(data) {
alert('form one sent');
$.ajax(
url: $('#form2').attr('action'),
type: $('#form2').attr('method'),
data: $('#form2').serialize()
).success(function(data) {
alert('form two sent');
})
});
});
This code isn't ready to be copy/pasted, it's just to give you a guideline of how I would solve it. It's a big question, try going with this solution and come back with smaller question if you find yourself blocked.
I have a popover with a form inside. And It is already out and ready for submission, here is the code for the popover
<div id="popover-head" class="hide">Add new subject</div>
<div id="popover-content" class="hide">
<form class="form-inline" id="pop-form" method="POST" action="../admin/module_add_subject.do">
<div class="form-group">
<!-- This input is what i'm talking about -->
<input type="text" name="subjectName" id="subject-name" required="required" pattern="^[\S\s]{3,25}[A-z]+$" title="Only accept alphabet characters and length is minimum of 3 and max of 25 " placeholder="Subject name.."/>
<button class="btn btn-primary" type="button" id="add-subject" ><i class="icon-white icon-ok"></i></button>
</div>
<p></p>
<p style="color:red" id="error-message"></p>
</form>
</div>
The input above I'm sure the regex is working. When I change the button to submitthe required is working perfectly fine but when I change it back to button then it is not working again.
The reason why my submit button is a type="button" because of this code:
$(document).on('click', '#add-subject', function(e) {
$.post('../admin/module_check_subject.do', { subjectName: $('#subject-name').val() },
function( data ) {
// if data from the database is empty string
if( $.trim( data ).length != 0 ) {
// hide pop-over
$('#popover').popover('hide');
// submit form
$('#pop-form').submit();
} else {
$('#error-message').text('Subject already exist.' );
}
}
})
.fail( function () {
bootbox.alert('Failed to check, please try again later.');
});
});
What I'm doing is on submit i'll check out first in my database if the input text in the textbox exist in the database, then if the text exist the database stop the submission of the form and display error at the p tag
By the form submission algorithm, validation is not performed when a form is submitted using the submit() method. The idea is, more or less, that when you submit a form with a script, your script should also carry out any checks deemed necessary.
Within your script, you can call the checkValidity() method to carry out the normal validation that would be performed if the form were submitted with a submit button. Note that it performs static validation only.