I have a Javascript function like this:
function validatePath()
{
var path = document.getElementById('server_path').value;
if (path.search(":") == -1)
{
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else
{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name)))
{
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
}
}
If the server_path is incorrect it displays the error but the form is still submitted. I don't want user to be able to submit the form until the server_path is correct. How can I do that?
The usual strategy is to use the form's submit handler and return false to stop submission if validation fails:
<form onsubmit="return validatePath();" ...>
Then in the function (pseudocode):
function validatePath() {
if (validation fails) {
return false;
}
// return any value other than false and the form will submit,
// including undefined
}
An other solution:
function validatePath() {
var path = document.getElementById('server_path').value;
var submitButton = document.getElementById('submit');
document.getElementById('path_error').innerHTML='';
submitButton.removeAttribute('disabled');
if (path.search(":") == -1){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
submitButton.setAttribute('disabled', 'disabled');
}
else{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name))){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
submitButton.setAttribute('disabled', 'disabled');
}
}
}
See in action: http://jsfiddle.net/rUcQc/.
You can disable the submit button until the path is correct. Like this
<input type='submit' disabled='true' onclick='return validatePath()' id='submit'/>
I made some changes in your javascript code.
function validatePath() {
var path = document.getElementById('server_path').value;
if (path.search(":") == -1){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name))){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else {
document.getElementById('submit').disabled=false;
}
}
}
Related
I have this newsletter form with email input generated with wordpress plugin. Form action is set to a sub-page. I want to check if given email adress is correct - if not, I want to print an alert message.
let emailField = document.querySelector('.email').value;
const regEx = /\S+#\S+\.\S+/;
let submitBtn = document.querySelector('.btn-submit');
let form = document.querySelectorAll('.newsletter-container > form');
function validateEmail() {
if (regEx.test(emailField) == false) {
alert('!!!');
event.preventDefault();
} else {
form.submit();
}
}
submitBtn.addEventListener('click', function (event) {
validateEmail();
});
My problem is, when I type a correct email adress I still get alert and button default event is prevented from action.
What am I doing wrong?
strange construct but anyhow
let submitBtn = document.querySelector('.btn-submit');
function validateEmail() {
var regEx = /\S+#\S+\.\S+/;
let emailField = document.querySelector('.email').value;
if (regEx.test(emailField) == false) {
alert('!!!');
event.preventDefault();
} else {
let form = document.querySelectorAll('.newsletter-container > form');
form.submit();
}
}
Before customers can proceed to paypal, I have a quick check on the database to see if the items still available,. The problem im having is that while Ajax is executing. function check_availability continue executing and returns true to the Form onsubmit before the completion of Ajax. To fix that problem I kept calling the same function within. But I dont think that is the best possible option.
Here is the code:
<form onsubmit="return check_availability(0,0,1)" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="pp1">
function ajax_paypal(orders){
var htpr = new XMLHttpRequest();
var url = "Hi there";
var val = "orders="+orders;
htpr.open("POST", url, true);
htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htpr.onreadystatechange = function(){
if(htpr.readyState == 4 && htpr.status == 200){
var sold_out_ids = htpr.responseText;
check_availability("continue", sold_out_ids, 0);
}
};
htpr.send(val);
}
function check_availability(str, sold_out_ids, n) {
if (str === "continue") {
if (sold_out_ids > 0) {
alert("One of your items has sold out! Sorry for any inconvenience");
location.reload();
return false;
} else {
return true;
}
}else if(n === 1){
var orders = [];
var x = document.cookie.split(';'); // your array of cookies
var i = 0;
x.forEach(item => {
//to make sure that item contains "order"
if (item.indexOf('order') > -1) {
var val = item.split("=");
orders[i] = val[1]+"o";
i++;
}
});
ajax_paypal(orders);
}
check_availability(0, 0, 0);//I keep calling this until Ajax is completed
}
You can use following code snippet to solve. This will be called on submit but before actual submit happen if you return true from here form will get submit to paypal. If you return false form won't get submit.
$('#pp1').submit(function() {
var submitOrNot=await callcheck_availability();
return true; // return false to cancel form submit
});
async function callcheck_availability(){
//your function goes here
}
for more on async await read this page on MDN
I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.
I wrote a script which allows me to validate a form with my Zend_Form validators instead of a classic client-side validation (like jQuery Validate) + server-side validation.
$(document).ready(function() {
var form = $('form'); // target form
var requests = [], validations = [];
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs (text/password) in the form
var cancelSubmit = true;
form.submit(function() {
// if we call the submit inside the function, skip validation
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations results
requests.length = 0;
validations.length = 0;
// for each input (text/password), get the validation status from the server
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
// and store the validation status
validations.push(0);
}
// else, remove error
else if(json.valid == 1) {
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
// and store the validation status
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.submit();
}
else
console.log('[-] There are still errors.');
}
});
});
});
return false;
});
});
The validation page server-side send a JSON : { valid: 0, message: "error message" } or { valid: 1}.
I can't have the form to be submitted. When I enter valid values, it does skip validation, but don't submit the form. I have to hit the submit button again to make it work (but, I could have entered non-valid values that wouldn't be checked in this time, as cancelSubmitis set to false).
Isn't return true; supposed to submit the form when used inside a .submit() ?
hi i am new enough to JavaScript and am wonder how to send details in email after validation ,heres my code
<script type="text/javascript">
var compName=false;
var compContry=false;
var compsub=false;
var compphone=false;
var compemail=false;
function validate_form(form)
{
if(compName)
{
document.getElementById('country').focus();
compName=true;
if(compContry)
{
document.getElementById('subject').focus();
compContry=true;
if(compsub)
{
document.getElementById('Phone').focus();
compsub=true;
if(compphone)
{
document.getElementById('email').focus();
compphone=true;
if(compemail)
{
//I just use alert to show it works.
alert("Your Details Are Sent ");
compemail=true;
}
else
{
document.getElementById('email').focus();
compemail=false;
}
}
else
{
document.getElementById('Phone').focus();
compphone=false;
}
}
else
{
document.getElementById('subject').focus();
compsub=false;
}
}
else
{
document.getElementById('country').focus();
compContry=false;
}
}
else
{
document.getElementById('username').focus();
compName=false;
}
}
You need some kind of server-side scripting to send emails.
After it passes validation you can submit your form like this
document.formname.submit();
in your case, this goes at the end of your function
if (comP... == true) {
form.submit();
}
you can add return false; after each validation if you are using cutom js
for example
var first_name = $("#first_name");
if(!$.trim(first_name.val()).length) {
first_name.closest('.form-group').removeClass('has-success').addClass('has-error');
return false;
}else{
first_name.closest('.form-group').removeClass('has-error').addClass('has-success');
}
return false will stop the submit button to proceed until the form is not filled.
freelancer