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/
Related
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 :-)
I have multiple input type text on jsp form for each the range is defined to the next input type textbox i want to validate with the defined range and if the value beyond the range validation function ask for pop confirmation if user enter userid in text that compare with session value ie 'user' then the validation function allow user to submit form with return true and not ask again for that filed validate .how can i achieve this using javascript function.any other way that can i achieve same using javascript .Request you to Suggest Option with example code.
JavaScript code:-
if(document.getElementById('pH'+formid).value !=0)
{
var user;
var value=document.getElementById('pH'+formid).value;
var maxmin=document.getElementById('pHspecf'+formid).value.split('-');
var max=maxmin[0];
var min=maxmin[1];
if(value<min||value>mix)
{
alert("max-"+max+" min-"+min+" value of parameter-"+value);
var c=confirm("Entered Value Beyond the Specification Range.\n DO you Still Want To continue Press Yes..!");
if (c==true)
{
var person=prompt("Please enter your Username","Your User name");
if (person!=null)
{user=person;
alert("Hello "+person+" Your Request Is Accepted..!");
}else{
document.getElementById('pH'+formid).style.backgroundColor = "lightblue";
document.getElementById('pH'+formid).focus();
return false;
}
}
else
{
document.getElementById('pH'+formid).focus();
return false;
}
}
}
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'm using gen_validatorv4.js from javascript-coder.com for validating forms. I love it because it's very simple to set up for normal use. But now I have run into a setup I can't fix.
This is what I'm trying to do. I have a form to edit users with fields for name, username and password etc. The problem is that I want the script to validate the password fields only when it's not empty.
I have tried this way but it doesn't work:
function DoCustomValidation() {
var frm = document.forms["edit_validate"];
if(frm.uPass.value != '') {
frmvalidator.addValidation("uPass","minlen=8","Minimum 8 characters")
frmvalidator.addValidation("uPass2","req","Passwords missing");
frmvalidator.addValidation("uPass2","eqelmnt=uPass","Password fields doesn't match");
frmvalidator.addValidation("uPass","neelmnt=uName","User name and password can't be the same");
return true;
} else {
return false;
}
}
frmvalidator.setAddnlValidationFunction(DoCustomValidation);
Any Idea anyone?
Regards Per
Just found this on ehow!
frmvalidator.addValidation("PASSWORD2","eqelmnt=PASSWORD",
"The confirmed password is not same as password");