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){
Related
Please i am trying to specify a pattern in the email input field in my form that it takes on lowercase words and if uppercase words are inputted in the email field it give an error and the form isn't submitted.
You can try this with javascript.
function checkText(e) {
const text = e.target.value;
if (text && (text === text.toUpperCase() || text.substr(-1) === text.substr(-1).toUpperCase()))
console.log('No upper case allowed')
}
<input type="text" oninput="checkText(event)">
Working FIddle
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");
}
});
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 using jquery regex to validate an email address, but i don't want this validation to be applied on empty field, please tell me how can i solve it
(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i)
Try this:
if($.trim($('textEmail').val()).length == 0){
//show some error
}
else{
//do your regex here
}
I just found this regex, and it doesn't validate any empty field for email address but checks if email entered in invalid, this worked for me
/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/
You can also try as
if($("#textEmail").val() == "" || $("#textEmail").val() == undefined)
{
alert("Please enter email");
}
else
{
//Regex Validation
//Other call as want
}
It's simple --
if($('#textEmail').val().trim() != ""){
//validate your Email
}
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.