So my form throws up the correct error when no email is given. But when a correct email is put into the field, it wont submit. Where am I going wrong here? Thanks for any advice and help!
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$(document).ready(function(){
$("#submitbutton").click(function(e){
var none_answered = true;
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
}
else {
$('#email').removeClass('error');
return true;
}
});
});
<style type="text/css">
.error
{
color:red;
}
#texthere
{
color:red;
}
</style>
<body>
<form>
<label id="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="email"></br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
</body>
You have duplicate IDs, for the label and input field. Because of that the value of eMailToTest was always blank.
<label for="email" class="req"><span>*</span>Email:</label>
Demo: Fiddle
Try to do like this:
$("#submitbutton").click(function (e) {
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if (!myEmailRegEx.test(eMailToTest)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
$('form').submit();
}
});
Also, seem like your none_answered variable is redundant here.
Try this change id of label
<form action="http://www.utah.edu/">
<label class="req"><span>*</span>Email:</label> // Here duplicate id removed
<input id="email" class="req" name="email" value="" type="email">
</br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" />
</form>
Script
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#submitbutton").click(function(e){
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if(!eMailToTest.match(myEmailRegEx)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
console.log('if')
}
else {
console.log('else')
$('#email').removeClass('error');
$(this).closest('form').submit();
}
});
DEMO
You did a few mistakes.
Use event submit on forms (not click event)
You used id attribute on label and email. ID can be used only once on page.
var eMailToTest = $('#email').val();
It returned value of first element with ID email. So it's label (which has no value). You want input element instead.
Here is the working code.
HTML:
<form>
<label for="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="text"><br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
Javascript:
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
(function(){
$("form").on('submit', function(e){
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
}
});
})();
Also none_answered variable is redundant here.
Working example.
Hope this helps :)
Related
I am trying to make a form with Materialize that validates one email. I start off with a submit button toggled to disabled. Ideally, when the email is filled in and validated, the submit button will stop being disabled and the user can click it to the next page. Here is my HTML:
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="text" name= "email" class="validate" required="" aria-required="true">
<label for="email">Email Address</label>
</div>
<br></br>
<a class="waves-light btn red lighten-2 disabled" id="submit">Submit
<i class="material-icons right">send</i>
</a>
<br></br>
<br></br>
<br></br>
</form>
Here is the JavaScript/jQuery:
$(document).ready(function(){
$('.parallax').parallax();
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
$('body').on('click', 'input', function() {
checkValidity($(this));
});
$('body').on('focusout', 'input', function() {
checkValidity($(this));
});
function checkValidity (current) {
let isValid = true;
if (!current.val()) {
isValid = false;
} else {
isValid = iteratatingForm(current);
}
const submit = $('#submit');
if (isValid) {
submit.removeClass('disabled');
} else {
if (!submit.hasClass('disabled')) {
submit.addClass('disabled');
}
}
}
function iteratatingForm (current) {
if (!document.forms['survey']['email'].value) return false;
return true;
}});
Please let me know what I'm doing wrong! Thanks!
You can use email type for your input and a button submit who will trigger validation input.
I added a function to check if email is valid with a regex. (Found here : How to validate email address in JavaScript? )
You have to add jQuery Validation Plugin
$(document).ready(function(){
$('#survey input').on('keyup', function(){
var validator = $("#survey").validate();
if (validator.form() && validateEmail($('#email').val())) {
$('#submitButton').prop('disabled', false);
$('#submitButton').removeClass('disabled');
}
else{
$('#submitButton').prop('disabled', true);
$('#submitButton').addClass('disabled');
}
} );
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email.toLowerCase());
}
/*
Confirmation Window
*/
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="email" name= "email" class="validate" required="true" aria-required="true">
<label for="email">Email Address</label>
</div>
<button type="submit" form="survey" value="Submit" class="waves-light btn red lighten-2 disabled" disabled='disabled' id="submitButton">Submit</button>
</form>
StackOverflow snippet bug due to jQuery validation plugin, but it works in CodePen
Another way to solve this is to add a regex field to your <input ... elements e.g.
<div class="input-field col s6">
<input id="email" type="text" class="validate" value="hello#email.com" regex="(?!.*\.\.)(^[^\.][^#\s]+#[^#\s]+\.[^#\s\.]+$)" required="" aria-required="true" value="hello#email.com" >
<label for="email">Email</label>
<span class="helper-text" data-error="Invalid email address."></span>
</div>
The nice thing about this is you can have individual regex validation for other fields. For example, you could have other inputs such as name / age e.g.
name (only contain groups of UPPER-CASE characters separated by a single space e.g. JAMES JONES - regex = ^[A-Z]*(\s[A-Z]+)*$).
age (only contain numbers - regex = ^\d+$).
NOTE: - I recommend the https://regex101.com/ website to test our your regex expressions against example text.
To validate using e.g. JQuery - you would add listeners to each of your input elements: -
$(document).ready(function(){
$("input").on('input propertychange blur', function(event) {
var elm = event.currentTarget;
var val = elm.value;
var isValid = true; // assume valid
// check if required field
if (elm.hasAttribute("required")) {
isValid = val.trim() !== '';
}
// now check if regex
if (isValid && elm.hasAttribute("regex")) {
var regex = new RegExp(elm.getAttribute("regex"), 'g');
isValid = regex.test(val);
}
elm.classList.remove(isValid ? "invalid" : "valid");
elm.classList.add(isValid ? "valid" : "invalid");
updateButtonState();
});
});
function updateButtonState () {
var numOfInvalid = $('input.invalid').length;
if (numOfInvalid > 0) {
$('.submit-button').prop('disabled', true);
$('.submit-button').addClass('disabled');
}
else{
$('.submit-button').prop('disabled', false);
$('.submit-button').removeClass('disabled');
}
}
When the page loads the JQuery function listens to changes to the input (and also blur events). It first of all checks if the input is a required field and validates that first. Next of all, it checks if a regex attribute exists, and if so, performs regular expression based validation.
If the validation fails, then the function adds/removes classes related to Materialize CSS and then finally updates the button state. This is optional but very nice if you are filling in a form (button is only enabled if everything is valid).
See the following CodePen to see everything in action: -
https://codepen.io/bobmarks/pen/oNGGvWq
So I currently have a download link and an input field for an email address on my website.
In order to download the file you first need to put in your email.
I use a form to do this, with the email field being an input field and the download button being a submit button.
I like HTML5's form validation (the required fields, field types etc, it all looks very nice).
The problem is that if I use onClick in my submit button then none of the nice form validation works.
<form>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" class="btn" onclick="downloadWin()" value="Windows">
<input type="submit" class="btn" onclick="downloadOsx()" value="Osx">
</form>
<script>
function downloadWin(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadWin&email='+email;
}
}
}
function downloadOsx(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadOsx&email='+email;
}
}
}
</script>
This might not be the cleanest way to do it, so please if you think you know a better way tell me :)
Try this:
<form onsubmit="download(this.email.value,this.system.value)" id="form">
<input type="email" id="email" name="email" placeholder="Please enter email" required>
<input type="radio" name="system" value="Win" required >Windows
<input type="radio" name="system" value="Osx" >Osx
<input type="submit" class="btn" value="Download">
</form>
<script type="text/javascript">
document.getElementById("form").addEventListener("submit", function(event){
event.preventDefault();
});
function download(email_value,sys_value){
location.href='http://s/index.php?page=download'+sys_value+'&email='+email_value;
}
</script>
Result:
try this code
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function downloadWin() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadWin&email=' + email;
}
}
return false;
}
function downloadOsx() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
return false;
}
Below is the working code snippet (without using HTML5 validation). You can run and test it. I have used the jquery with jquery.validate plugin. You can uncomment the commented code to redirect user to the target url. Let us know if this what you are looking for or not. Feel free to comment if there is anything that you feel confusing.
$(document).ready(function(){
$(".btn-download").on("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($("#validateForm").valid()) {
var name = $(this).val();
var email = $("#email").val();
if (name === "Windows") {
//location.href = 'http://s/index.php?page=downloadWin&email=' + email;
console.log('http://s/index.php?page=downloadWin&email=' + email);
}
if (name === "Osx") {
console.log('http://s/index.php?page=downloadOsx&email=' + email);
//location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<form method="post" action="" id="validateForm" novalidate>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" name="btnSubmit" class="btn btn-download" value="Windows">
<input type="submit" name="btnSubmit" class="btn btn-download" value="Osx">
</form>
i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>
I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">
I can't figure out why the script isn't working with the form. Why doesn't the $("form").submit(function() call the form with id form? This script isn't even performing the window.onbeforeunload so I guess the script is faulty. Does anyone know what's wrong?
<form id="formID" class="access_form" name="form" method="post" action="site.com">
<div class="row">
<label for="email">Email Address:</label>
<input class="txt_email" type="text" id="email" name="email" value="" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" />
</div>
<div class="row">
<input type="submit" class="btn_access" value="Get Immediate Access" name="submit1" />
</div>
</form>
JavaScript:
var formHasChanged = false;
var submitted = false;
$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form
select, form.confirm-navigation-form textarea', function (e) {
formHasChanged = true;
});
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (formHasChanged && !submitted) {
var message = "Please enter your email", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
$("#formID").submit(function () {
submitted = true;
});
});
just try this.The id of the form is form itself.So select the form like this using jQuery
$("#form").submit(function () {
submitted = true;
});
OR
Or try giving another id for the form for example "formID".Then select using that id like this.
$("#formID").submit(function () {
submitted = true;
});