jquery.validate - button disabled until valid email - javascript

I am using https://jqueryvalidation.org/ to validate my form on the frontend. The basic "if field is empty - validate" works OK.
But I'd like to the submit button to be initially disabled until a valid email address has been entered. I'd like the button to become enabled as soon as the field becomes valid (on keypress).
So basically I just need to remove the 'btn-disabled' class once its valid.
I'm struggling with the jQuery to add this function/method. Would be grateful if someone can help out.
Heres a slightly simplifed version: http://codepen.io/dagford/pen/kXJpEZ
$(document).ready(function(){
$("#reset-form").validate({
rules: {
emailaddress: {
required: true,
email: true
}
},
messages: {
email: "Please enter a valid email address"
}
});
});

you can check if the form is valid after entering the email address. Keep you button disabled by default and remove the disabled attribute once you validate the form.
$("#emailaddress").on("blur", function(){
if($("#reset-form").valid())
{
$("#btn-reset").removeAttr("disabled");
}
});
Code Pen : http://codepen.io/anon/pen/YWLjKX?editors=1010

You have attr for this
$('#button1, #button2').attr("disabled", true);

Check this :
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') { // write your code for valid email here
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>

Related

Do not search if the search field is empty (Wordpress)

I have this basic Wordpress search form, I don't want users to be able to search if they leave the search field blank, preferably with javascript, how is this done?
Many ways lead to Rome... But here is one solution.
So, say your search form input field has and id called query and you want to disable the submit button until the user has entered at least 1 character.
$('#query').keyup(function () {
if ($(this).val() == '') {
$('#submit').prop('disabled', true);
} else {
$('#submit').prop('disabled', false);
}
}).keyup();
See this fiddle: https://jsfiddle.net/fxqsc86s/
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})();
and remember to disable the button by default:
<input type="submit" id="search" value="Search" disabled="disabled" />
Answer taken from previous stack overflow question: Disabling submit button until all fields have values
You can also do it like this.
It will check either your TextBox is empty
if ($('#TextBoxId').val() === '') {
// Your coding will go here.
}

Form Validation w/Javascript - Not working

I have the following form, done with HTML and Javascript validation.
var submitOK=true;
function validate(){
submitOK=true;
checkName();
checkSurname();
checkCourse();
checkDate();
checkEmail();
if(submitOK == false) {
return false;}
}
function checkName() {
var name = document.getElementById("name");
if(myform.name.value.length==0)
{
document.getElementById("checkname").innerHTML="Please, enter a valid name";
submitOK=false;
}
}
(COMPLETE CODE IN HERE)
http://jsfiddle.net/unkok6or/
The fields Course, Date, Name, Surname and Email have to be required. I don't know why my code is wrong and how to fix it.
-What I would like, is an error message to appear if one of the fields is not complete. Now the form runs and works even if one of them is not completed.
-The email with the correct format (without Regex).
Thanks in advance! :)
I simplified your code a little bit. This worked for me. The key thing to remember that your submit function must return a true to submit or false to stop the submit.
var submitOK=true;
function validate(){
submitOK=true;
checkName();
checkSurname();
checkCourse();
checkDate();
checkEmail();
return submitOK;
}
function checkName() {
if( document.getElementById("name").value.length==0)
{
document.getElementById("checkname").innerHTML="Please, enter a valid name";
submitOK=false;
}
}
function checkSurname() {
if(document.getElementById("surname").value.length==0)
{
document.getElementById("checksurname").innerHTML="Please, enter a valid surname";
submitOK=false;
}
}
function checkEmail() {
if(document.getElementById("email").value.length==0)
{
document.getElementById("checkemail").innerHTML="Please, enter an email";
submitOK=false;
}
}
function checkCourse() {
if(document.getElementById("course").selectedIndex < 1 ) {
document.getElementById("checkcourse").innerHTML="Please, select a course";
submitOK=false;
}
}
function checkDate() {
if(document.getElementById("date").selectedIndex < 1) {
document.getElementById("checkdate").innerHTML="Please, select a date";
submitOK=false;
}
}
You need to return true when your validation passes so change
if(submitOK == false) {
return false;}
to
return submitOk;
If you just need to make sure all the fields are filled, why don't you use required keyword on ur input types.
And for drop down you can disable the select option that way you don't need to check if the user has selected the default value.

Problems with validate jquery function

I was trying to make a validation in my form with jquery, but it does not work the way it was supposed to and I have no idea why.
I have this function to make the validation:
function newLogin () {
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
if (username == "" || password.length<5){
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
});
return false;
}
else{
Parse.User.logIn(username, password, {
success:function(user){
console.log("login successfull");
if(checkEmail()){
console.log(checkEmail());
document.location.href = "Temas.html";
}
},
error: function(user, error){
console.log(error.message);
displayErrorDiv();
}
})
}
}
And i got this form
<form id = "popup-login-form">
<input type="email" name="email" placeholder="Email" id = "popup-login-email" class="popup-input first"/>
<div id="error-message-email" class="error">
</div>
<input type="password" name="password" placeholder = "Password" id="popup-login-password" class="popup-input"/>
<div id="error-message-password" class="error">
</div>
<button class="popup-button" id="popup-cancel">Cancel</button>
<button type="submit" class="popup-button" id="popup-submit">Login</button>
<div class="error-message-login" class="error">
</div>
</form>
And the weird part is that just does not work in my page. Here it works, for example: http://jsfiddle.net/xs5vrrso/
There is no problem with the code which you shared in jsfiddle but the above code you are using $(document).ready({function()}) inside a function which is of no use. Now the problem is that the method newLogin is not called on dom ready and thus this issue occurs.
Better keep the function call inside $(document).ready({function() newLogin() }) . Now you can also use submitHandler in validate to merge the if else conditions.
i make one example to you
jsfiddler example
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
//event listening onSubmit
$('form').submit(function(event){
var returnForm = true;
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
//Make your validation here
if (username == "" || password.length<5){
returnForm = false;
}
return returnForm; //Submit if variable is true
});
});
With jQuery when i get the
"TypeError: $(...).validate is not a function"
I change
$(..).validate
for
jQuery(..).validate
You have to include this validate file after jquery file.
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
Do not wrap the code under the if condition with $(document).ready(). Change the code to :
if (username == "" || password.length < 5){
$("#popup-login-form").validate({ // initialize the plugin
/*remaining code here*/
});
}
Also it is a good habit to trim the spaces around any input that you accept from the users. For e.g in your case please do the following:
var username = $.trim($("#popup-login-email").val());
var password = $.trim($("#popup-login-password").val());
/* $.trim() would remove the whitespace from the beginning and end of a string.*/

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

JQuery validation-input text field to be required if checkbox checked

I have the following checkbox:
<input type="checkbox" id="startClientFromWeb" name="startClientFromWeb" data-bind="checked: StartClientFromWeb" />
and the following input text field:
<input id="mimeType" name="mimeType" data-bind= "value: MimeType" />
This is my js validation code:
$("#franchiseForm").validate({
rules: {
mimeType: {
required: $("#startClientFromWeb").is(":checked")
}
}
});
I want the mimeType input text field to be required only if checkbox is checked. For some reason the above is not working. I am quite new to javascript and jquery. Any help with working example will be greatly appreciated. Thank You!
You can add your own custom validation methods to handle things like this:
$.validator.addMethod("requiredIfChecked", function (val, ele, arg) {
if ($("#startClientFromWeb").is(":checked") && ($.trim(val) == '')) { return false; }
return true;
}, "This field is required if startClientFromWeb is checked...");
$("#franchiseForm").validate({
rules: {
mimeType: { requiredIfChecked: true }
}
});
Validation will not triger if input is disabled. You could use that fact - let textbox be required, but initially disabled, and enable it only when checkbox is checked.
$(function () {
$('#startClientFromWeb').change(function () {
if ($(this).is(':checked')) {
$('#mimeType').removeAttr('disabled');
}
else {
$('#mimeType').attr('disabled', 'disabled');
}
});
});
The simpliest way which works:
rules : {mimeType:{required:"#startClientFromWeb:checked"}}, messages: {mimeType: {required: 'Repeat checked, To date required'}}

Categories