Validating E-Mail address using JavaScript or JQuery - javascript

I have to validate E-Mail address using either JS or JQ.
Right now I am using JS but unable to pass the value of the text box as the parameter for JS. I want this to be implemented onchange.
I found solutions only using a button to validate which i don't want to.
Here is the HTML code.
<div class="form-group">
<label class="control-label">Father's E-Mail Address</label>
<input maxlength="30" pattern=".{1,50}" onchange="validateEmail(document.getElementById('txtFatherEmail').value);" title="Input Invalid" type="text" required="required" class="form-control" placeholder="Enter Father's E-Mail Address" id="txtFatherEmail" runat="server"/>
</div>
Here is the JS I have used.
function validateEmail(email) {
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if (!valid) {
alert("False");
} else {
alert("True");
}
}
Also I would like to know if there's any better way to do this.

If I understand correctly you want to validate input as you type.
To do this you can use onkeyup event.
<div class="form-group">
<label class="control-label">Father's E-Mail Address</label>
<input maxlength="30" pattern=".{1,50}" onkeyup="validateEmail(this.value);" title="Input Invalid" type="text" required="required" class="form-control" placeholder="Enter Father's E-Mail Address" id="txtFatherEmail" runat="server"/>
</div>

Why are you using getElementById with "value"? Shouldn't you be using thee jquery syntax? Remember a jquery element is not a javasript don element. Maybe that's the trick...

function isvalid(x){
regexp1 = /#/g
gmail = /gmail.com/g
hotmail = /hotmail.com/g
if(regexp1.test(x) == true){
if(x.match(regexp1).length == 1){
x = x.split("#")
if(gmail.test(x[1]) == true){
if(x[1].match(gmail).length == 1 && x[1].length == 9){
alert("ok valid")
}else{
alert("not valid")
}
}else if(hotmail.test(x[1]) == true){
if(x[1].match(hotmail).length == 1 && x[1].length == 11){
alert("ok valid")
}else{
alert("not valid")
}
}else{
alert("no mail")
}
}else{
alert("too much #")
}
}else{
alert("no #")
}
}
this function is the jquery email check function and it just looks for gmail and hotmail and if you want just to check email from hot and gmail it is the reliable function for it

Related

Create a guestbook application in HTML with some conditions in the input fields

I want to create a guestbook application page in HTML which has 3 fields for the user to input:
Name
E-mail
Message
I wanna make the client check in JavaScript, so below are my snippets of code which I added in the head of the html page.
For the Name I need to put a condition so only letters can be entered, no numbers, no special characters, no spaces or empty field, so I made this
function Validate()
{
var x=document.forms["guest"]["email"].value;
var y=document.forms["guest"]["name"].value;
var regex=/^[a-zA-Z]+$/;
if( y==null || y=="" || (!y.match(regex)))
{
alert("Please enter your Name! ");
return false;
}
My question is: How can I insert a condition so the name must be bigger than 3 letters?
For the e-mail field I made this:
if(x==null || x=="")
{
alert("Please enter your email address!");
return false;
}
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
return true;
}
Here I don`t have any question.
For the message field I need to add a condition so the message must be bigger than 10 characters.
Can you help me with that?
Thanks
You really dont even need javascript for this:
<form action="">
<input type="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" name="email" required title="Valid email required" required>
<br>
<input type="text" pattern="[a-zA-Z]{3,}" name="name" required title="Letters only and at least 4 characters" required>
<br>
<input type="text" pattern=".{10,}" name="message" required title="10 characters minimum" required>
<br>
<button>Submit</button>
</form>
You should take a look into the length property.
E.g.:
var y=document.forms["guest"]["name"].value;
if(y.length < 3) {
alert("Not a valid name");
return false;
}
Further informations for the length property on w3schools
An other option is to use the HTML5 minlength attribute:
<label>Username: <input name=u required minlength=3></label>
Further informations for the minlength attribute on W3

How to make email id in a form optional in JavaScript

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">

Correct value but program still says it wrong

I am new to html and coding in general.Hope someone can help me,thank in advance.I want it to alarm if i put wrong value but even if i put correct value it still alarm me.Here is my script:
$(document).ready(function() {
$("#name").blur(function(){
var value = this.value;
if(isNaN(value)){
alert("Wrong!Please enter your name again");
}
});
$("#email").blur(function(){
var value = this.value;
if(isNaN(value)){
alert("Wrong!Please enter your email again");
}
});
$("#submit").click(function(){
alert("Your message has been sent successfully!Thank you.")
});
});
And my code in jetbrain:
<div class="col-sm-6 form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="text" required>
</div>
<div class="col-sm-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required>
</div>
I think it's on your isnan jquery function. Please don't use that kind of function when validating inputs like emails. Instead you should create a variable to test whether the inputs contain valid characters.
For example:
$('#email').blur(function() {
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test(this.value)) alert('passed');
else alert('failed');
});
isNaN = is not a number.
You are checking if the input is numeric.
You probably want something like this:
if ($('#name').is(':empty')){
//do something
}
So in your case:
$(document).ready(function() {
$("#name").blur(function(){
if ($('#name').is(':empty')){
alert("Wrong!Please enter your name again");
}
});
$("#email").blur(function(){
if ($('#email').is(':empty')){
alert("Wrong!Please enter your email again");
}
});
$("#submit").click(function(){
alert("Your message has been sent successfully!Thank you.")
});
}
you just use those function in on submit because on blur not hold the submit process when user entred wrong value and try to submit it so that use like this.
$("#submit").click(function(){
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
if ($('#name').val()==''){
alert("Wrong!Please enter your name");
return false;
}
if ($('#email').val()=='' || !pattern.test($('#email').val())){
alert("Wrong!Please enter Proper email");
return false;
}
alert("Your message has been sent successfully!Thank you.")
});

Javascript validation nightmare

I'm trying to get my "username" and "password" fields to verify that there is information in them before submitting the form.
What should I need to add to my HTML and to my JavaScript to have them work! If you want to suggest a new JavaScript, please do!
HTML:
<form action="validateForm.html" id="registrationForm">
<label for="username" id="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" value="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" id="passwordLabel">* Password:</label>
<input type="password" name="password" id="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" id="submit" />
</form>
JavaScript
function validateForm()
{
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
if(!document.forms[0].username){
alert("Username field is required!");
}
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
}
One way would be getting your input by id and then validate its value
HTML
<input type="text" id="username" />
<input type="password" id="password" />
JS
function validateForm()
{
if(!document.getElementById("username").value) // true if input value is null, undefined or ""
{
alert("Username field is required!");
}
else if(!document.getElementById("password").value)
{
alert("Username field is required!");
}
}
(i strongly recommend you to use more attractive ways of giving users feedback than JS alerts)
I think all of those checks are incorrect in some for, let's start with the first one:
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
It's document.getElementsByName() (notice the plural)
The function returns an array of elements, so you'd still need to check for the value of the one you want (probably 0)
This is going to be true always as the field exist, you need to check the value in the input, but right now you are just checking the existence of the input.
Next one is similar:
if(!document.forms[0].username){
alert("Username field is required!");
}
You are checking the existence of the field, not its value
This type of selection is not recommended, you should be using a document.getElementBy... better.
And finally:
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
It looks like you tried to make a for loop but copy-pasted from above and got this mess... not even going to try to understand why the loop.
Recommendations:
Use the attribute id and read the fields using document.getElementById()
To check if a field has content, check its value: .value
Add an event handler for the form (onsubmit="validateForm()")
Make the form validator return false if one of the fields is incorrect (otherwise the form will be sent even with the incorrect fields)
Optionally: use the HTML5 required attribute.
So the function would look like:
function validateForm()
{
if(document.getElementById("username").value == "")
{
alert("Username field is required!");
return false;
}
// check the other fields
// .....
}
May I suggest something like this instead:
HTML:
<form action="validateForm.html" onSubmit="return validateForm(this)">
<label for="username" name="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" placeholder="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" name="passwordLabel">* Password:</label>
<input type="password" name="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" />
</form>
JS:
function isEmpty (field) {
return field.value === "";
}
function validateForm (form) {
// assume the form to be valid
var isValid = true;
// create a variable to store any errors
var errors = "";
// check if the username is empty
if(isEmpty(form.username)) {
// our assumption is incorrect, the form is invalid
isValid = false;
// append the error message to the string
errors += "Username field is required!\n";
}
if (isEmpty(form.password)) {
isValid = false;
errors += "Password field is required!\n";
}
// display the errors if the form is invalid
if (!isValid) {
alert(errors);
}
return isValid;
}
This way, you are passing the form directly to the validateForm function and can easily access each field using their name properties. You can then check if they're empty by determining what their value contains.
If you need to get the DOM by it name means it will returns an Array so you need to get it by
if(!document.getElementsByName("username")[0].value == ""){
//do ur stuff
}
or
if(!document.getElementById("username").value == ""){
//do ur stuff
}

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Categories

Resources