Form: Validate special cases with jQuery before form submission - javascript

I need to validate a form without using any special plugin, just jQuery.
I have a disabled SUBMIT button which I am enabling like this:
const getFields = $(
'form#inquiry-component-form input, form#inquiry-component-form textarea, form#inquiry-component-form select'
).filter('[required]:visible');
getFields.on('input', () => {
let empty = false;
getFields.each(function() {
if (!empty && $(this).val() == '') {
empty = true;
}
});
$('#submit-inquiry-form').prop('disabled', empty);
});
The problem I am having is that the form contains a phone number and email address inputs, so the submit button will become enabled when those 2 inputs are not empty anymore. I need them to match the pattern first, then the submit button gets enabled.
These are the tel and email inputs:
<input id="inquiry-phone" class="form-control" type="tel" name="phone" placeholder="Phone Number (10 digits)" pattern="[1-9]{1}[0-9]{9}" required>
<input id="inquiry-email" class="form-control" type="email" name="email" placeholder="Email address" required>
Any ideas?

You can try something like this. I added a submit button and then we're checking to enable the button or not using regex.
<form id="submit-inquiry-form">
<input id="inquiry-phone" class="form-control" type="tel" name="phone" placeholder="Phone Number (10 digits)" pattern="[1-9]{1}[0-9]{9}" required>
<input id="inquiry-email" class="form-control" type="email" name="email" placeholder="Email address" required>
<button id="btn" disabled>Submit</button>
</form>
const getFields = $(
'input'
).filter('[required]:visible');
getFields.on('input', () => {
let empty = false;
let patternMatch = true;
getFields.each(function() {
console.log("check", $(this).val())
if ($(this).val().trim() == '') {
empty = true;
}
// check for regex
if ($(this).attr("pattern")) {
const regex = new RegExp($(this).attr("pattern"));
patternMatch = regex.test($(this).val())
}
});
if (empty || !patternMatch) {
console.log("empty or bad match")
$('#btn').attr('disabled', true);
} else {
$('#btn').removeAttr('disabled');
}
});

Related

JQuery how to validate form inputs and textarea on whitespace and empty?

I am trying to validate multiple form elements such as <input> and <textarea> but I cant seem to get it to work. I tried getting the values from the form by putting the values in an array and looping through it but it doesn't work.
if (!checkform($('#myform'))) {
alert("Please fill all required fields");
} else {
// do something
}
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.serializeArray();
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if (inputs[i].value.trim == null || inputs[i].value.trim === '') {
// found an empty field that is required
return false;
}
}
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myform">
<label class="form-label">Firstname</label>
<input type="text" name="firstname" class="form-control" id="firstname" required>
<label class="form-label">Message</label>
<textarea id="message" type="text" rows="3" name="message" placeholder="enter your message">
</textarea>
</form>
Your trim is wrong - it should be inputs[i].value.trim() === ""
Also you did not assign the validation to the form submit
$('#myform').on("submit",function(e) {
if (checkform($(this))) return true;
alert("Please fill all required fields");
e.preventDefault()
});
function checkform($form) {
// get all the inputs within the submitted form
var inputs = $form.serializeArray();
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if (inputs[i].value.trim() === '') {
// found an empty field that is required
return false;
}
}
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myform">
<label class="form-label">Firstname</label>
<input type="text" name="firstname" class="form-control" id="firstname" required>
<label class="form-label">Message</label>
<textarea id="message" type="text" rows="3" name="message" placeholder="enter your message">
</textarea>
<input type="submit" />
</form>

How to disable submit button until all mandatory fields are filled using html and vanilla js

How to disable submit button until the user enters all fields and also how to use event listener on submit form.
<form action='index.html' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
const init = function () {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(username,password,email)
};
Jsfiddle link
Set up a validation object with booleans to record if all your values have met validation.
Then I'd loop through all your inputs and add an event listener to each of them. In this example I've checked to see if each has at least one character in them, but you might want to expand on this.
Finally, loop through your validation object and check if all the values are true. If they are, remove the disabled attribute from the button.
let inputs = document.querySelectorAll('input');
let buttonSend = document.getElementById('button-send');
let inputValidator = {
"username": false,
"email": false,
"password": false
}
inputs.forEach((input) => {
input.addEventListener('input', () => {
let name = event.target.getAttribute('name');
if (event.target.value.length > 0) {
inputValidator[name] = true;
} else {
inputValidator[name] = false;
};
let allTrue = Object.keys(inputValidator).every((item) => {
return inputValidator[item] === true
});
if (allTrue) {
buttonSend.disabled = false;
} else {
buttonSend.disabled = true;
}
})
})
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send' disabled>SUBMIT</button>
</form>
This is probably not what you are looking for but you can achieve almost the same effect by simply using the required attribute in your input fields:
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username" required>
<input type="email" name="email" id="email" placeholder="email" required>
<input type="password" name="password" id="password" placeholder="password" required>
<button type="submit" name="submit" id='button-send' >SUBMIT</button>
</form>
Using the onBlur event will ensure the user has visited each field. You may also want to check the field contains a value, for that you can add the HTML required attribute.
var isDirty = {
username: false,
password: false,
email: false
}
const init = function() {
let incompleteItems = getIncompleteItems();
if(incompleteItems.length > 0) {
alert(`${incompleteItems} requires a value.`);
return;
}
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(`values: ${username}, ${email}, ${password}`);
};
const onChange = function(e) {
isDirty[e.id] = true;
}
const getIncompleteItems = function() {
let incomplete = "";
for (const [key, value] of Object.entries(isDirty)) {
if(value === false) {
if(incomplete.length > 0) {
incomplete += `, ${key}`;
}
else {
incomplete = key;
}
}
}
return incomplete;
}
<form method='GET' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username" onBlur="onChange(this)">
<input type="email" name="email" id="email" placeholder="email" onBlur="onChange(this)">
<input type="password" name="password" id="password" placeholder="password" onBlur="onChange(this)">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
Create a validation function which will check all the validations and sets the disabled property of the button if validation fails and vice versa. Call the validation function on every change of all the fields.
You can use oninput event
<input type="text" oninput="validate()">

Check if fields have valid class and are not empty before enabling submit button?

I asked this question earlier with no luck, so I am trying again with better wording and hopefully I can resolve my issue.
I have been working on a small form which has a few inputs, three of which have regex validation (email, number and postcode). I have a function which checks if all fields in the form are filled before enabling the submit button, however if the previously mentioned fields are invalid (but filled), the button will still be enabled and allow submission. I am looking to try and incorporate a check if the fields are also valid before enabling the submit button.
I have been trying at this since 7am with no luck, I have tried checking if they have class is-invalid to disable button, I tried to implement the jQuery Validate plugin (which I didn't find very useful), and really I have hit a bit of a wall and don't know what else to do.
I can find plenty of answers on checking valid input, and plenty on checking if forms are filled completely, but none which incorporate both, and I've tried to do it myself and it's not working. Any help is, as always, appreciated.
Here's what I have:
// ~~~ phone number validation
function validateContact(number) {
var re = /^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/;
return re.test(number);
}
function validateC() {
var number = $("#number").val();
if (validateContact(number)) {
$("#number").removeClass("is-invalid");
return true;
} else {
alert('Please enter a valid phone number');
$("#number").addClass("is-invalid");
}
return false;
}
// ~~~ email validation
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 validateE() {
var email = $("#email").val();
if (validateEmail(email)) {
$("#email").removeClass("is-invalid");
// $("#submit").removeClass("toggle-disabled").prop("disabled", false);
return true;
} else {
alert('Please enter a valid email address.');
$("#email").addClass("is-invalid");
// $("#submit").addClass("toggle-disabled").prop("disabled", true);
}
return false;
}
// ~~~ postcode validation
function validatePostcode(postcode) {
var re = /^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$/;
return re.test(postcode);
}
function validateP() {
var postcode = $("#postcode").val();
if (validatePostcode(postcode)) {
$("#postcode").removeClass("is-invalid");
return true;
} else {
alert('Please enter a valid postcode');
$("#postcode").addClass("is-invalid");
}
return false;
}
// ~~~ validate if form is filled completely, toggles submit & edit button
$(document).on('change keyup', '.required', function(e) {
var disabled = true;
// var isValid = false;
$(".required").each(function() {
var value = this.value;
if ((value) && (value.trim() != '')) {
disabled = false;
$('.toggle-disabled').prop("disabled", false);
} else {
disabled = true;
$('.toggle-disabled').prop("disabled", true);
return false;
}
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<div class="col-md-6">
<input type="email" class="input form-control required" id="email" onchange="validateE()" placeholder="Email Address" name="email">
</div>
<div class="col-md-6">
<input type="tel" class="input number form-control required" id="number" onchange="validateC()" placeholder="Contact Number" name="Number" required>
</div>
<div class="col-md-6">
<input type="text" id="postcode" class="input postcode form-control required" onchange="validateP()" placeholder="Post Code" name="postcode" required>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit" disabled>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Instead of && use || because here if any one of the condition is true you need to disable your submit button . Then , add one extra condition $(this).hasClass('is-invalid')) for checking if the inputs are valid or not .
Demo code :
// ~~~ phone number validation
function validateContact(number) {
var re = /^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/;
return re.test(number);
}
function validateC() {
var number = $("#number").val();
if (validateContact(number)) {
$("#number").removeClass("is-invalid");
return true;
} else {
alert('Please enter a valid phone number');
$("#number").addClass("is-invalid");
}
return false;
}
// ~~~ email validation
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 validateE() {
var email = $("#email").val();
if (validateEmail(email)) {
$("#email").removeClass("is-invalid");
// $("#submit").removeClass("toggle-disabled").prop("disabled", false);
return true;
} else {
alert('Please enter a valid email address.');
$("#email").addClass("is-invalid");
// $("#submit").addClass("toggle-disabled").prop("disabled", true);
}
return false;
}
// ~~~ postcode validation
function validatePostcode(postcode) {
var re = /^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$/;
return re.test(postcode);
}
function validateP() {
var postcode = $("#postcode").val();
if (validatePostcode(postcode)) {
$("#postcode").removeClass("is-invalid");
return true;
} else {
alert('Please enter a valid postcode');
$("#postcode").addClass("is-invalid");
}
return false;
}
// ~~~ validate if form is filled completely, toggles submit & edit button
$(document).on('change keyup', '.required', function(e) {
var disabled = true;
$(".required").each(function() {
var value = this.value;
//using or also added hasclass('is-invalid')
if (!(value) || (value.trim() === '') || ($(this).hasClass('is-invalid'))) {
disabled = false;
$('.toggle-disabled').prop("disabled", true);
}
});
//check disabled if true then also enabled.
if (disabled) {
$('.toggle-disabled').prop("disabled", false);
}
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<div class="col-md-6">
<input type="email" class="input form-control required" id="email" onchange="validateE()" placeholder="Email Address" name="email">
</div>
<div class="col-md-6">
<input type="tel" class="input number form-control required" id="number" onchange="validateC()" placeholder="Contact Number" name="Number" required>
</div>
<div class="col-md-6">
<input type="text" id="postcode" class="input postcode form-control required" onchange="validateP()" placeholder="Post Code" name="postcode" required>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit" disabled>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

Submitting Form W/ Javascript

My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/

Categories