I want to do a very basic jQuery validation of an email via a regex on submit. My HTML:
<form action="POST" id="form">
<input type="email" id="customer_email" placeholder="email here" />
<input type="submit" />
</form>
JS:
$('#form').submit(function() {
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').value();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
To my understanding, for this to work I need to get the value of the input via email input (which I do on line 4) and run a regex on it.
When submit is clicked, the standard input error appears on the form, and not the window alert. Feel free to view a Codepen outlining this here:
http://codepen.io/anon/pen/oYmJLW?editors=1010
You need to add event.preventDefault() to prevent the actual form submission, and use .val() instead of .value() on the input.
$('#form').submit(function(event) {
event.preventDefault();
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').val();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
By declaring your input as type="email" your browser will do the validity checking (you don't need to do it yourself then), if you want to circumvent that use type="text".
Related
I am trying to check if all form fields are filled on click a button & if valid then i am trying to add a check an alert using jquery.
jQuery("button#btn_place_order").click(function(event){
jQuery("form").validate({
submitHandler: function(form) {
alert('ok');
}
});
});
This is what i have tried but its not working, i just want to check if all fields are ok valid & filled & there is no form related error then just console or alert to check. Webpage has two or more html forms. Is their any way we can check using jquery ?
Thanks
First of you will have to prevent the default behavior of a form submit. Afterwards add a event listener to your button and check for validation of each input. (whatever that means for you). Is this what you wanted?
var el = document.getElementById("form");
el.addEventListener("submit", function(event) {
event.preventDefault();
}, true);
document.getElementById("btn").addEventListener("click", validate);
function validate(){
let valid = true;
[...document.getElementById("form").elements].forEach((input) => {
if(input.value.length == 0){
valid = false;
}
});
if(valid) alert("valid");
}
<form id="form">
<input type="text" name="TEST" id="test">
</form>
<button class="button" name="Send" value="Send" id="btn">Check</button>
I'm trying to send messaging to the user that a field is required if they fail to input a value. I want the error to be displayed on the field itself, rather than a global error message at the top of the page.
If I do not enter any data into the form, it still allows submission. However, if I do not enter a username but I do enter mismatched passwords, the username field receives the validation message "Passwords do not match".
So, it appears to me, that for some reason my code to check if the input is null is not passing as True and so the function continues to my next condition.
Why isn't this function catching nulls?
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"
oninput="checkNull(this)" id="username">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password" oninput="checkNull(this)"
id="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmPassword" placeholder="Confirm Password" type="password"
oninput="check(this)" id="confirmPassword">
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
} else {
input.setCustomValidity('');
}
}
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
}
else {
input.setCustomValidity('');
}
</script>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I've tried some additional troubleshooting. I split my functions out, one to check for matching passwords, one to check for no input. I realized that by calling them in the same function I was comparing each to the password which is a problem.
As a sanity check, I then set to check for a specific string "foo". When passing in "foo", the error displays as expected, so I know at least the function is getting called.
I then tried to use "===" to compare the value rather than "==", but that didn't work either.
Code updated to reflect most recent changes.
When submit your form, it is not calling check() function. So, if you not touch any input, they will not be validated.
You can solve this by adding onsubmit="return validate()" to <form /> tag:
<form action="/register" method="post" onsubmit="return validate()">
Your validation function could be simple as:
var isValid = true;
function validate() {
isValid = true;
document.querySelectorAll('.form-control').forEach(check);
return isValid;
}
Notice the return keyword. When return value is false the submitting action will be cancelled. check() function should also mutate isValid variable:
function check(input) {
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
isValid = false;
}
else if (input.type == 'password' && input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
isValid = false;
}
else {
input.setCustomValidity('');
}
}
Also, you should only check if passwords are the same if you are validating a password input.
You can accomplish this by adding the extra condition to password validation: input.type == 'password'
You are calling your check method onchange, if you do not enter any text in the username field, your check method will not be called. So, the simple way to do this is to add required attribute on all your fields.
If you want to do it using JS, look at onsubmit method that gets triggered when the form's submit button is clicked.
Also, you should have three different methods for validating each of your fields. It will be hard to maintain and you will be cramping up one method with various checks.
You are using deprecated techniques here.. You should never attach a function to a form element in-line (within the html tag).
When it comes to checking password on keyup, you could use something like this with jquery:
var pwInputs = $(this).find('input[type=password]');
$('input[type=password]').keyup(() => {
pwarr = new Array();
pwInputs.each(function() {
pwarr.push($(this));
});
if (pwarr[0].val() != pwarr[1].val()) {
// Do work
}
if (pwarr[0].val() == null || pwarr[0].val() == "" & pwarr[1].val() == null || pwarr[1].val() == "") {
// Do Work
}
});
You could use jquery in a similar fashion to check values on submit.
$('#formid').on('submit', function() { // Do work })
I am working on jquery validation with form action php submit. I created jquery validation using click function first time it's validate the input field on second click it's redirecting to form action url. How to prevent this using client side validation. How can i solve this.
<form action="test.php" method="post">
<input class="qemail" name="your-email-address" placeholder="Your email address" value="" type="text">
<textarea class="qmessage" name="your-enquiry" rows="8" placeholder="Your message"></textarea>
<input id="submit_sf" name="enquiry-submit" value="SUBMIT" type="submit">
</form>
$(document).ready(function(){
$('input[name="enquiry-submit"]').click(function(){
var email = $('.qemail').val();
var msg = $('.qmessage').val();
var email_regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
if(!email.match(email_regex) || email.length == 0 ){
if ($('.qemail').prev(".rvalidation").length == 0){
$('.qemail').before('<p class="rvalidation" style="position:relative; color: #000; font-size:12px;">Please enter a valid Details *</p>');
$(".qemail").focus();
console.log("email field is empty");
$(".qemail").focus();
//console.log("validate1"); \
return false;
}
//return false;
}
if(msg.length == 0){
console.log("message field is empty");
return false;
}
});
});
change type = "button"
<button id="submit_sf" name="enquiry-submit" value="SUBMIT" type="button">Submit</button>
The function() within the .click event can accept an argument for the event handler.
$('input[name="enquiry-submit"]').click(function(ev) { ...
You can use ev.preventDefault(); to keep the post from actually occurring until validation has passed. You'll need to manually trigger the form post though.
$('input[name="enquiry-submit"]').click(function(ev) {
ev.preventDefault();
...
}
I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)
I have a webpage where a user submits a form containing an email field and a confirm email field.
How do I check to make sure both of these fields equal the same thing?
<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>
With jQuery, but no error handling, I'd suggest:
$('form').on('submit', function() {
return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});
Ridiculously simple JS Fiddle demo.
Easiest way would be to use Javascript as you can stop form submission before it goes to your php file. However it is still good practice to verify the data entered with the php file as well as there are some programs that will allow you to change data being submitted in a form after javascript checks are made.
<script>
function checkMatch() {
var email = document.getElementById('email').value;
var emailConfirm = document.getElementById('emailConfirm').value;
if (email != emailConfirm) {
alert("Email addresses are not the same.");
return false; //Returning 'false' will cancel form submission
} else {
/*
place the return true; at the end of the function if you do other
checking and just have if conditions and return them as false. If
one thing returns false the form submission is cancelled.
*/
return true;
}
}
</script>
And change your form to have onSubmit
<form method="post" action="submit_query.php" onSubmit="checkMatch()">
Add id's to your email inputs such as: email and emailConfirm. You can change them if you wish but just for an example I used those.