So I have two fields in my webpage, one for telephone number and the other for email address, I need to make either one of them required to be filled by using JavaScript NOT jQuery. Most of the answers I found here are for jQuery, any solutions with JavaScript would be much appreciated. Thanks!
function User_one(){
var phone = document.getElementById('PhoneText2').value;
var mail = document.getElementById('EmailText1').value;
if (phone && mail == ""){
alert("An error occurred.");
}else{
return false;
}
}
Update with actual code
Here's how I'd do it
(function () {
document.getElementById('myForm').addEventListener('submit', function(event){
// Get the length of the values of each input
var phone = document.getElementById('PhoneText2').value.length,
email = document.getElementById('EmailText1').value.length;
// If both fields are empty stop the form from submitting
if( phone === 0 && email === 0 ) {
event.preventDefault();
}
}, false);
})();
Since you haven't supplied any code for us to work with, I'll answer in pseudo-code:
On form submission {
If (both telephone and email is empty) {
throw validation error
}
otherwise {
submit the form
}
}
If you show me your code I'll show you mine :-)
Related
As am not good with JS and Jquery, am struggling to add new validation rule to the Marketo form, which shows error message when tried to submit the form leaving any field empty along with I need to validate the FirstName and LastName fields to allow only the alphabetic characters and should through a error message when numeric characters are entered.
Below is my Marketo LP: http://qliktest.qlik.com/Vinu-Test1_Reg_Form.html
Here is an example of custom email validation. You can put the custom code in whenReady function.
MktoForms2.whenReady(function(form) {
function isEmailValid(email) {
RE_EMAIL_ASCII_PUBLIC = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
return RE_EMAIL_ASCII_PUBLIC.test(email);
}
form.onValidate(function() {
var values = form.vals();
if (values.Email) {
if (!isEmailValid(values.Email)) {
form.submitable(false);
var emailElem = form.getFormElem().find("#Email");
form.showErrorMessage(
// write your message here
"Must be valid email.",
emailElem
);
} else {
form.submitable(true);
}
}
});
If you mark the fields as "required" in Marketo there is already logic built in that will take care of the validation for you. If you want to create some custom validation logic, I.E. only allowing alphabetic characters in the fields, you need to use the Marketo Forms 2.0 Javascript API (http://developers.marketo.com/documentation/websites/forms-2-0/)
Here's an example of validating a Marketo form field using the API:
MktoForms2.whenReady(function (form) {
//listen for the validate event
form.onValidate(function() {
// Get the values
var vals = form.vals();
//Check your condition
if (vals.Country == "USA" && vals.vehicleSize != "Massive") {
// Prevent form submission
form.submittable(false);
// Show error message, pointed at VehicleSize element
var vehicleSizeElem = form.getFormElem().find("#vehicleSize");
form.showErrorMessage("All Americans must have a massive vehicle", vehicleSizeElem);
}
else {
// Enable submission for those who met the criteria
form.submittable(true);
} }); });
I am trying to make a simple web application. In my login page I have a form with a text field, a password and a submit button. Form submission is prevented if either fields are empty. This is the script I use:
function checkLoginCredentials() {
var usernameFormValue = $("#usernameForm").val().trim();
var passwordFormValue = $("#passwordForm").val().trim();
var validated;
$("#loginForm").submit(function(event){
if (usernameFormValue === "" || passwordFormValue === "") {
$("span").html("Enter a username or password");
validated = false
} else {
validated = true;
}
return validated;
});
}
However, I noticed that once the script runs and form submission is prevented, the user can no longer make an attempt to log in again. The only alternative I can think of is to have ALL validations done by my login servlet and utility classes. Is there a way around this or must validations of invalid entries like empty strings be done by my Java Classes?
The issue here is how you are assigning the validation code. You have a checkLoginCredentials and when you call it you read the form values. And than you add a form submission. You should add the reading of the textbox values inside of the submit method, not outside.
$("#loginForm").submit(function(event){
var usernameFormValue = $("#usernameForm").val().trim(),
passwordFormValue = $("#passwordForm").val().trim(),
validated;
if (usernameFormValue === "" || passwordFormValue === "") {
$("span").html("Enter a username or password");
validated = false
} else {
validated = true;
}
return validated;
});
I'm trying to compare two form inputs "password" and re-enter-password" to make sure there the same. I validate the password by sending it to a separate PHP that echoes back the results(which works fine)
<script type="text/javascript">
$(document).ready(function() {
$('#password_feedback').load('password-check.php').show();
$('#password_input').keyup(function() {
$.post('password-check.php', {
password: form.password.value
},
function(result) {
$('#password_feedback').html(result).show();
});
});
});
</script>
I tried sending password and re-enter=password to a PHP to compare with no luck. Can I compare the two with every keyup.
What are you checking for in your PHP script? Anything in particular that justifies the use of PHP?
You could do that only with JS, you don't need the AJAX part.
HTML :
<input type="password" id="password">
<input type="password" id="password_cf">
<div class="result"></div>
JS (jQuery) :
$('#password_cf').on('keyup', function(){
if($('#password_cf').val()== $('#password').val())
$('.result').html('They match');
else
$('.result').html('They do not match');
});
Fiddle : http://jsfiddle.net/2sapjxnu/
You can use the blur event if you want to only check once the focus is lost on that field. It's a bit less "responsive" than verifying on every key, but more performant I guess.
Not necessary jQuery, add the function:
function checkPass(input) {
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
Add this to your re-enter-password: oninput="checkPass(this)"
OR
just call this function in the part where you want to make the comparison:
function checkPass() {
var input = document.getElementById('password');
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
How about adding a class to each input and then:
if($(".password").val() == $(".re-enter-password").val()){
alert("it matches")
} else {
alert("no match yet");
}
Quick and dirty -
Given this markup -
<input type="password" name="pw1" />
<input type="password" name="pw2" />
You could check it client side without muliple round trips to the server using code like this -
$('[name="pw2"]').blur(function() {
var pw1 = $('[name="pw1"]').val();
var pw2 = $('[name="pw2"]').val();
if(pw2 != pw1) {
alert('passwords do not match');
}
});
Matching 2 form input fields with JavaScript by sending it off to the server to get an assertion response could render a bad user experience, because if you're doing this on each keyPress, then it generates unnecessary internet traffic - while the user is waiting.
So, instead, why not match these 2 fields directly with JavaScript?
If you are using a specific regular expression on the server for validation check as well, you can have the server put that regex "pattern" in the HTML fields - (no JavaScrpt needed for that). Then, onkeyup event you can simply do something like:
form.field2.onkeyup = function()
{
if (form.field1.value !== form.field2.value)
{
/* some code to highlight the 2 fields,
or show some message, or speech bubble */
return;
}
}
form.field1.onkeyup = form.field2.onkeyup;
I have a forgot password form. It has two fields 1) email and 2) mobile. So what I need is a validation for it. like both field should not be empty, both field should not be filled, any one only should be filled. email should be in email format and mobile should only contain numbers.
javascript Code:
function validate_fgtmgrpwd(){
var adminid=document.f_mgr_password.mgrid;
var adminmobile=document.f_mgr_password.mgrmobile;
var mgr_length=document.f_mgr_password.mgrmobile.value;
if ((document.f_mgr_password.mgrid=="Ex: ManagerID#Email.com")||
(document.f_mgr_password.mgrid==""))
{}
{document.getElementById("validationMessage").innerHTML=" <font color='#FF0000'>Error: </font> Please Enter Either Email Id Or Mobile No:!";
popup('validationPopup');
mgrid.focus();
return false;
}
}
You should do the validation server side, not client side. There are always ways to get around your javascript form validation.
So you should check/validate the POST values in your php script, and act accordingly.
With html5 you can define an input type="email" for your email field ( so it parse properly inserted email ) and an input type="tel" for your mobile phone field. So, set the clear field at onfocus event for the other field. this should works fine.
Try this:
function validate_fgtmgrpwd() {
var adminid = document.f_mgr_password.mgrid,
adminmobile = document.f_mgr_password.mgrmobile,
emailExp = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/gi,
phoneExp = /^[0-9\-\+]{9,15}$/gi;
if(!adminid.value.length && !adminmobile.value.length){
alert("At Least one field is mandatory!");
adminid.focus();
return false;
} else {
if(adminid.value.length && !emailExp.test(adminid.value)){
alert("Enter a valid email");
adminid.focus();
return false;
} else if(adminmobile.value.length && !phoneExp.test(adminmobile.value)) {
alert("Enter a valid phone number");
adminmobile.focus();
return false;
} else {
return true;
}
}
}
For HTML5 supporting browsers, native validation will work and for other browsers, custom validation will work.
jsfiddle: http://jsfiddle.net/MR6bD/2/
I am working with a form that has a catcha image. When a user fills out the form, and presses submit ( and only when the captcha number is wrong) the fields are reset or cleared. How can I prevent this from happening?
If a visitor fills out the form, presses submit, the expected behaviour is theform is submitted, or if the captch number is wrong, retain the information that the visitor had input in the fields and ask the visitor to fill in the correct captcha number...
Here is the js:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
When you want to prevent the default behaviour you've to use a callback function like this:
function onsubmit_handler(evt) {
if (/* validation is ok */) {
return true;
}
else { /* validation is not ok */
evt.preventDefault();
return false;
}
}
yourfom.onsubmit = onsubmit_handler;
Am I correct in believing that the captcha is validated (only) on the server after a successful validation by the JS (i.e., not via an Ajax call in the form submission event handler)? Am I further correct in believing that you're doing a true HTML form submission instead of an Ajax form submission in the background?
If both of those are true, then the problem probably isn't in your JavaScript at all (I say "probably" only because you could conceivably have a JS function that clears all the form fields on load or something like that). You're submitting the form to the server, the server looks at the captcha, sees that the answer is wrong, and displays the form again -- with blank values. You need to change your server code to include the user's previous answers as value attributes (or selected options or whatever as appropriate for the element type) when it writes the form after a server-side validation failure.