Below is a script on a HTML input form. My problem is that when for the first time I enter something in the input box I get the wrong result, but when I focus on the box again (click in the input box) and then deselect the input box I get the right answer! why this is happening??? what is the solution?
<input type="email" id="iemail" name="email" class="form-control"></input>
<script>
var pattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var userinput;
$("#iemail").focus(function(){
userinput = $("#iemail").val();
});
$("#iemail").blur(function(){
if(pattern.test(userinput)){
alert("VALID");
}else{
alert("not a valid e-mail address");
}
});
</script>
could anybody please help me. I will really appreciate it...
It's because you're assigning a value to userInput on the focus event of the field, which for the first time focus is triggered, when the field is blank, will mean userInput is set to a blank value.
You could move the assignment of userInput to the blur event instead.
var pattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
$("#iemail").blur(function(){
var userinput = $("#iemail").val();
if(pattern.test(userinput)){
alert("VALID");
}else{
alert("not a valid e-mail address");
}
});
Remove this :
$("#iemail").focus(function(){
userinput = $("#iemail").val();
});
change blur to :
$("#iemail").blur(function(){
userinput = $("#iemail").val();
if(pattern.test(userinput)){
alert("VALID");
}else{
alert("not a valid e-mail address");
}
});
The reason is because you are globally storing the value of #iemail on focus. The first time it focuses, it globally stores an empty string since you haven't type anything yet. When you blur, it checks that empty global string. The second time you focus, it now has a value in the text box and stores that.
No need to do these things separately.
$("#iemail").blur(function(){
var userinput = $("#iemail").val();
if(pattern.test(userinput)){
alert("VALID");
}else{
alert("not a valid e-mail address");
}
});
Related
I am new with JavaScript validation and learning I am trying to validate form but I am getting issue with condition.
In my form I have one field which is name and one submit button.
What I am trying is:
If user click to to submit button and text box is empty give alert('Please enter your First Name.')
Then If user entered value which is not allowed by regex give alert('Please enter only letters no special character allowed.');
but I am getting first alert every time. Whats wrong i don't understand.
My Code:
jQuery('#send').click(function () {
var reg_first_name = /^[A-Za-z ]{3,20}$/;
var first_name = jQuery('#sa_first_name').val();
if(first_name.length > 0){
alert('Please enter your First Name.');
document.getElementById("sa_first_name").focus();
return false;
}
if (!reg_first_name.test(first_name)) {
alert('Please enter only letters no special character allowed.');
document.getElementById("sa_first_name").focus();
return false;
}
return false;
});
Can you guide me?
In case the user enters a name the first_name.length > 0 will always be true.
You can check it like
if($.trim(first_name) == '')
to also avoid only spaces
condition is wrong
if(first_name.length > 0){
if you want to check that first_name must have value then your condition must be
if(first_name.trim().length == 0){
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 have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric
i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.
It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.
<script>
function validate(){
u=document.CustomerLogin.UserName.value;
p=document.CustomerLogin.Password.value;
rp=document.CustomerLogin.RePassword.value;
if (u==""){
document.write("Enter a unique username");
return false;
}
if (p!=rp){
document.write("Retype Password Incorrect");
return false;
}
return true;
}
</script>
The messages are printed on separate page but i want them to be printed at the same place in front of text box! Please help. Thanks!
Never use Document write, it's hazardous...
document.getElementById("anidofanElementinthePage").innerHTML = " string to add by javascript";
<script>
function validate(){
u=document.CustomerLogin.UserName.value;
p=document.CustomerLogin.Password.value;
rp=document.CustomerLogin.RePassword.value;
if (u==""){
document.getElementById("theIdOfyourTextBlocInForm").innerHTML = "Enter a unique username";
return false;
}
if (p!=rp){
document.getElementById("theIdOfyourTextBlocInForm").innerHTML = "Retype Password Incorrect";
return false;
}
return true;
}
</script>
document.write will simply append the message to the end of the page. The simplest solution would be change it to an alert like this:
if (u==""){
alert("Enter a unique username");
return false;
}
Otherwise you will need to create new DOM elements(either before hand or when an error is detected) to hold the message and position them next to the inputs
you would need to detect text change. One way is to use this:
<input name="blah" onchange="validate()" ... />
EDIT
To add text on the same page, include the script using <script src=...> and then add <div id='validation[i]'></div> next to each of the inputs where [i] is increased by 1 each time (so validation1 validation2 so on). Then, use getElementById('validation[i]').innerHtml to change the value.
How can i check if a html5 input field is empty? I am trying to override the native validation message given by using a required text input.
This is how my code looks now:
<script>
$(document).ready(function(){
H5F.setup(document.getElementById("contact-form"));
var name = document.getElementById("contact-name")
if (name.value === "") {
name.setCustomValidity("Please fill out the field with your name");
}
});
</script>
Here what u need.. a full guide about how to change this native validation message :D
http://afarkas.github.io/webshim/demos/demos/forms.html#Locale-Settings
Wrapping your code in a blur listener should do the trick.
var name = document.getElementById("contact-name");
$(name).blur(function(){
if (name.value === "") {
name.setCustomValidity("Please fill out the field with your name");
}
});