Using jQuery to prevent form submission when input fields are empty - javascript

The solution should be pretty straightforward. I'm trying to prevent the form from submitting properly when no value is found within the input boxes. Here's my JSFiddle: http://jsfiddle.net/nArYa/7/
//Markup
<form action="" method="post" name="form" id="form">
<input type="text" placeholder="Your email*" name="email" id="email">
<input type="text" placeholder="Your name*" autocomplete=off name="name" id="user_name"
<button type="submit" id="signup" value="Sign me up!">Sign Up</button>
</form>
//jQuery
if ($.trim($("#email, #user_name").val()) === "") {
$('#form').submit(function(e) {
e.preventDefault();
alert('you did not fill out one of the fields');
})
}
As you can see in the JSFiddle, the problem is that when I type something into both fields, the alert box STILL pops up. I'm having a hard time figuring out why. Is there something wrong within my
if($.trim($"#email, #user_name").val()) === "") ?

Two things, #1 the check for empty fields should happen on every attempt of submit, #2 you need to check each field individually
$('#form').submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
alert('you did not fill out one of the fields');
return false;
}
});
Updated fiddle

Your check occurs on page load. You need to check the field when the form is submitted.
$('#form').submit(function(e) {
if ($.trim($("#email, #user_name").val()) === "") {
e.preventDefault();
alert('you did not fill out one of the fields');
}
});

HTML5: use required in input tag
A boolean attribute.
Input field must be filled out before submitting the form.
Works with text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
<input required type='text'...>
w3schools hint

I guess that this will help:
$('#form').submit(function(e) {
e.preventDefault();
$("#email, #user_name").each(function(){
if($.trim(this.value) == ""){
alert('you did not fill out one of the fields');
} else {
// Submit
}
})
})

Put your if statement inside the callback:
$('#form').submit(function(e) {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val())) {
e.preventDefault();
alert('you did not fill out one of the fields');
//You can return false here as well
}
});

Related

Jquery validating not empty and is URL in forms

I'm using the following fiddle to create a form and check that both fields are not empty and that the second field is a valid URL.
http://jsfiddle.net/nc6NW/366/
<form method=post>
<input type="text" id='first_name'>
<input type="url" id='second_name'>
<input type="submit" value="Submit" id="submit" disabled>
</form>
<script>
$(':text').keyup(function() {
if($('#first_name').val() != "" && $('#second_name').val() != "") {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
</script>
However it only works when you return to amend the first field after adding the URL
The :text is the issue.
Update your jQuery to the below
$("input").keyup(function() {
if($('#first_name').val() != "" && $('#second_name').val() != "") {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
You are listening to ':text' keyup. Because your second input is an 'url' type, it do not trigger the function.
That's why you have to go back to first input.
The events are being triggered only on keyup of the first input field. Add a similar keyup event to the second field and it will work

Trying to validate form field with jQuery

I know I must be missing something super simple here, because in theory this code is supposed to work, but it's not, and I cannot understand why. I'm trying to work out my own jQuery form validation, because I tried the jQuery form validator plug-in, and while setting up the rules and messages is perfectly simple, figuring out how to get the error message to show up where I wanted it to was a nightmare (couldn't get the message to show up AFTER radio buttons, for example.)
I've got the 1st part of my attempted validation working, but I can't clear the message once you enter something in the field. Also, the message pops up even when conditions are met, which doesn't make sense to me.
here's the jsfiddle
html
<form>
<p>
<lable for="name">Enter your name:</lable>
<input type="text" id="name" name="name">
<span class="error"></span>
</p>
<lable for="age">Enter your Age:</lable>
<input type="text" id="age" name="age" width="3">
<span class="error"></span>
</p>
</form>
jQuery
$("input").focusin(function(){//highlight input field on focus
$(this).css("background-color", "yellow");
});
$("input").focusout(function(){
$(this).css("background-color", "white");
});
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this))){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
$("#name").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this)) != false){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
$("#age").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
You forgot the $(this).val()
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this).val())){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
and again at age
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this).val())){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
also you can remove != false - e.g
if (test != false)
is the same as
if (test)
Heres the fixed up fiddle
Need to Remember Some thing while validating form Using JS:-
Check input value Using (this).val();
if Error Occur then forward to next vale with Error .
Check test value is false or true using if (test != false) or if (test)
then forward your Control for success page
You can use the lettersonly rule.
Here's an example:
Define a variable validator and do this :
validator = $("form").validate({
rules: {
name: { required: true,
lettersonly: true
}
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate() call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
you need to call
$("form").valid()
and if it is valid means without any errors then do :
validator.hideErrors();
$("form" div.has-error").removeClass("has-error");
For age input for numeric only jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

validate mobile number in javascript

I want to validate my mobile number using javascript and my code is:
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length == 10){
alert("success");
}
else{
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
and calling function is:
<input type="text" name="Contact-No." id="textbox" required >Contact(Mobile No.)
<input type="submit" value="Submit" onclick="checkLength()">
All works fine but after showing alert message it should be return on same page but it takes me to some other blank page.
remove the onClick event from button and add onSubmit to <form..>.
Something like <form onSubmit='return checkLength();>'.
1) Your form needs to prevent the default submit action so that if you find error the form doesnt actually submit.. you should hook into the onsubmit event in your form.
an example assuming you've included jQuery 1.7+ on the page
html
<form id="myform" action="/">
<input type="text" name="Contact-No." id="textbox" />
Contact(Mobile No.)<br><br>
<input type="submit" value="Submit" id="submit" />
</form>
javascript
$("#myform").on("submit",function(e){
if(checkLength()==false){
alert('prevent form submit');
e.preventDefault();
}else{
alert('form submits as normal');
}
});
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length == 10){
alert("success");
return true;
}
else{
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
example at:
http://jsfiddle.net/Lqbn6unp/
As pointed out elsewhere, the listener should be on the form's submit handler since the form can be submitted without pressing the submit button. Also, you can reference form controls as named properties of the form, which is more efficient than using getElementById and means the control doesn't need an ID.
So pass a reference to the form from the listener, e.g.
In the form:
<form onsubmit="return checkLength(this)" ... >
<input type="text" name="Contact-No." required >Contact(Mobile No.)
then in the function:
function checkLength(form) {
var textbox = form['Contact-No'];
if (textbox.value.length == 10) {
alert("success");
} else {
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}

Set custom HTML5 required field validation message

Required field custom validation
I have one form with many input fields. I have put html5 validations
<input type="text" name="topicName" id="topicName" required />
when I submit the form without filling this textbox it shows default message like
"Please fill out this field"
Can anyone please help me to edit this message?
I have a javascript code to edit it, but it's not working
$(document).ready(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter Room Topic Title");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
Email custom validations
I have following HTML form
<form id="myform">
<input id="email" name="email" type="email" />
<input type="submit" />
</form>
Validation messages I want like.
Required field: Please Enter Email Address
Wrong Email: 'testing#.com' is not a Valid Email Address. (here, entered email address displayed in textbox)
I have tried this.
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");
}
else {
input.setCustomValidity("");
}
}
This function is not working properly, Do you have any other way to do this? It would be appreciated.
Code snippet
Since this answer got very much attention, here is a nice configurable snippet I came up with:
/**
* #author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* #link https://stackoverflow.com/a/16069817/603003
* #license MIT 2013-2015 ComFreek
* #license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
Usage
→ jsFiddle
<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",
emptyText: "Please enter an email address!",
invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});
More details
defaultText is displayed initially
emptyText is displayed when the input is empty (was cleared)
invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)
You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.
Compatibility
Tested in:
Chrome Canary 47.0.2
IE 11
Microsoft Edge (using the up-to-date version as of 28/08/2015)
Firefox 40.0.3
Opera 31.0
Old answer
You can see the old revision here: https://stackoverflow.com/revisions/16069817/6
You can simply achieve this using oninvalid attribute,
checkout this demo code
<form>
<input type="email" pattern="[^#]*#[^#]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>
Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP
HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
function InvalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Required email address');
}
else if (textbox.validity.typeMismatch){{
textbox.setCustomValidity('please enter a valid email address');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/
Try this:
$(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("Please enter Room Topic Title");
};
}
})
I tested this in Chrome and FF and it worked in both browsers.
Man, I never have done that in HTML 5 but I'll try. Take a look on this fiddle.
I have used some jQuery, HTML5 native events and properties and a custom attribute on input tag(this may cause problem if you try to validade your code). I didn't tested in all browsers but I think it may work.
This is the field validation JavaScript code with jQuery:
$(document).ready(function()
{
$('input[required], input[required="required"]').each(function(i, e)
{
e.oninput = function(el)
{
el.target.setCustomValidity("");
if (el.target.type == "email")
{
if (el.target.validity.patternMismatch)
{
el.target.setCustomValidity("E-mail format invalid.");
if (el.target.validity.typeMismatch)
{
el.target.setCustomValidity("An e-mail address must be given.");
}
}
}
};
e.oninvalid = function(el)
{
el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
};
});
});
Nice. Here is the simple form html:
<form method="post" action="" id="validation">
<input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
<input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />
<input type="submit" value="Send it!" />
</form>
The attribute requiredmessage is the custom attribute I talked about. You can set your message for each required field there cause jQuery will get from it when it will display the error message. You don't have to set each field right on JavaScript, jQuery does it for you. That regex seems to be fine(at least it block your testing#.com! haha)
As you can see on fiddle, I make an extra validation of submit form event(this goes on document.ready too):
$("#validation").on("submit", function(e)
{
for (var i = 0; i < e.target.length; i++)
{
if (!e.target[i].validity.valid)
{
window.alert(e.target.attributes.requiredmessage.value);
e.target.focus();
return false;
}
}
});
I hope this works or helps you in anyway.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.
[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);
emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});
The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.
Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.
Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/
Hope that helps!
Just need to get the element and use the method setCustomValidity.
Example
var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
Use the attribute "title" in every input tag and write a message on it
you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!
Here is my demo codes!(you can run it to check out!)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oninvalid</title>
</head>
<body>
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
<input type="email" placeholder="xgqfrms#email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
<input type="submit" value="Submit">
</form>
</body>
</html>
reference link
http://caniuse.com/#feat=form-validation
https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation
You can add this script for showing your own message.
<script>
input = document.getElementById("topicName");
input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write
input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});
</script>
For other validation like pattern mismatch you can add addtional if else condition
like
else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}
there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid
use it on the onvalid attribute as follows
oninvalid="this.setCustomValidity('Special Characters are not allowed')

'success' dialog after jquery form validation clears and submits - showing success message no matter what

I have a simple email form:
<form method="post" action="process-form.php" id="emailForm" name="emailForm" target="_self">
<h4>Sign up to be notified when we go live!</h4>
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
<input type="submit" name="submit" id="submit" value="Submit" onclick="return alert('Thanks! Your email has been added.');">
<p>emails will not be shared with third parties</p>
</form>
I am using the following jQuery validation:
/*
Created 09/27/09
Questions/Comments: jorenrapini#gmail.com
COPYRIGHT NOTICE
Copyright 2009 Joren Rapini
*/
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#emailForm").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
After the form validates successfully I want a success dialog to display. I kind of have that going now with the onClick event for the submit button but obviously that is going to display the message no matter if it validates or not. I think the message needs to be placed in the validation somewhere.
At the end of your onsubmit function, where you return 'true'.

Categories

Resources