Email and mobile number validation on same html5 textbox with button - javascript

I want to validate both email,mobile number using single textbox.
I tried in many ways but not working. i want to validate either it is javascript,html5,jquery,angularjs is not a problem.
please help me to solve this problem. thanks in advance
http://jsfiddle.net/ANxmv/3582/
<form name="form" ng-app="app" ng-controller="Ctrl" >
<div class="control-group" ng-class="{true: 'error'}[submitted && form.email.$invalid]">
<label class="control-label" for="email">Your email address/Mobile number</label>
<div class="controls">
<input type="email" name="email" ng-model="email" required />
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>

here is the simple javascript code which will validate both email and phone number.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
function ValidateEmail(mail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
// if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
if(mail.match(mailformat))
{ alert(mail);
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
function validate()
{
var data=document.getElementById("email").value;
checkNumberorEmail();
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.match(phoneno)))
{
alert(inputtxt);
return true;
}
else
{
alert("enter 10 digit number");
return false;
}
}
function checkNumberorEmail()
{
var data=document.getElementById("email").value;
if (isNaN(data))
{
ValidateEmail(data) ;
}
else{
phonenumber(data)
}
}
</script>
</head>
<body>
<form >
<input type="text" name="email" id="email">
<input type="button" onclick="validate()">
</form>
</body>
</html>
FIDDLE

The method itself is not good. But here is a possible simple function in angular js
HTML
<form name="form" ng-app="app" ng-controller="Ctrl" >
<div class="control-group" ng-class="{invalidClass: 'error'}[submitted && form.email.$invalid]">
<label class="control-label" for="email">Your email address/Mobile number</label>
<div class="controls">
<input type="text" name="email" ng-model="email" required />
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitForm()">Submit</button></form>
Controller
$scope.submitForm = function(){
if(validateEmail($scope.email) || validateMobile($scope.email)){
// The nput is email or mobile
}
else{
//both are not valid
console.log("Invalid inputs");
$scope.invalidClass = true;
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateMobile(email) {
var re = /^\d{10}$/;
return re.test(email);
}

Related

preventDefault() cause problem on validating the form

the code below was written to validate simple html form with JavaScript and preventDefault() method means that if the required fields are empty then stop form submission and display error or otherwise submit the form if the required fields are not empty.
The problem comes when I click the submit button the form isn't working.
Can anyone please help me to solve the problem?
let form = document.getElementById("signUp");
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
function validateForm() {
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
e.preventDefault();
validateForm();
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
With e.preventDefault() you say that the form should not be submitted.
So you only want to call if in case the validation returns false.
Besides that, your uname and uemail is set before the form is submitted. So it won't contain the state of the input fields at the time the form is submitted. You have to move them into your validateForm function.
let form = document.getElementById("signUp");
function validateForm() {
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
if (!validateForm()) {
e.preventDefault();
}
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
And uname == " " does not test if the name is empty. It tests if it consists of one character that is a space. The same is for uemail == " ". You probably looking for uname.trim() == ""
As you need to verify the data on the server anyways. And in some way need to display an error if the validation fails on the server side.
It is often sufficient to rely on the HTML solutions to verify the form data (if the browser support is decent enough even if it is not complete).
Something like this:
.error {
display: none;
}
input:not(:placeholder-shown):invalid +.error {
display: block;
}
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName" placeholder="Name" pattern="^(?!^ +$)([\w -&]+)$" required>
<div class="error">Name must not be empty</div>
<br> Email: <input type="email" name="email" id="userEmail" placeholder="Email" required>
<div class="error">Email must be valid</div>
<button type="submit">sign up</button>
</form>
const form = document.getElementById("signUp");
form.addEventListener("submit", (e) => {
e.preventDefault();
if(validate()) {
form.submit()
}
});
const validate = () => {
const name = document.querySelector("#userName");
const email = document.querySelector("#email");
let hasError = false;
if(!(name.value && name.value.length > 4)) {
const nameErr = document.querySelector("#user-name-error");
nameErr.textContent = "Name is required";
hasError = true;
}
if(!(name.value && name.value.length > 0)) {
const emailErr = document.querySelector("#user-email-error");
emailErr.textContent = "Email is required";
hasError = true;
}
return !hasError;
};
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" />
<p id="user-name-error" style="color: red;"></p>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" />
<p id="user-email-error" style="color: red;"></p>
</div>
<button type="submit">sign up</button>
</form>
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" required minlength="4"/>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" required pattern="[^#]*#[^.]*\..*"/>
</div>
<button type="submit">sign up</button>
</form>
This is an example using only html, it is only for your use case of course if you want to add more complexe validation use javascript

when onsubmit event in form only first function is working i want to return all 3 function with true

Ajax code to check email is new or existing
I want all the three function return(checkpass() && check() && validate(this)) to work. Currently only the function checkpass() is working. If I write return(check() && checkpass() && validate(this)), only check() function gets triggered.
function check(){
var uname=document.forms["register_form"]["uname"].value;
var uemail=document.forms["register_form"]["uemail"].value;
var upassword=document.forms["register_form"]["upassword"].value;
var ucpassword=document.forms["register_form"]["ucpassword"].value;
if(uname=="" || uemail=="" || upassword=="" || ucpassword==""){
alert("all fields must be filled out");
return false;
}
}
function checkpass(){
var upass=document.forms["register_form"]["upassword"].value;
var ucpass=document.forms["register_form"]["ucpassword"].value;
if(upass!=ucpass){
alert("Confirm password should be same as password");
return false;
}
if(upass=="" && ucpass==""){
alert("cannot be kept blank");
return false;
}
}
function validate(useremail){
xhttp =new XMLHttpRequest();
xhttp.open("GET","emailvalidate.php?uemail="+useremail,true);
xhttp.send();
xhttp.onreadystatechange=function(){
if (xhttp.readyState == 4) {
if(xhttp.responseText==""){
document.getElementById("alert").innerHTML="cannot be empty";
return false;
}
else if(xhttp.responseText=="OK"){
document.getElementById("alert").innerHTML="<span class='badge badge-pill badge-primary'>welcome new user</span>";
}
else if(xhttp.responseText=="NO"){
document.getElementById("alert").innerHTML="<span class='badge badge-pill badge-primary'>Email Already Exist</span>";
return false;
}
else{
document.getElementById("alert").innerHTML="error happened";
return false;
}
}
};
}
<form method="post" action="register_action.php" id="register_form" name="register_form" onsubmit="return (checkpass() && check() && validate(this));">
<br>
<div class="form-group">
<label for="uname">Name:</label>
<input type="text" class="form-control" id="uname" placeholder="Enter Name " name="uname">
</div>
<div class="form-group">
<label for="uemail">Email id: </label>
<input type="email" class="form-control" id="uemail" placeholder="Enter Email ID" name="uemail"
onkeyup="javascript:validate(this.value)"><br>
<span id="alert"></span>
</div>
<div class="form-group">
<label for="upassword">Enter Password:</label>
<input type="password" class="form-control" id="upassword" placeholder="Set password" name="upassword">
</div>
<div class="form-group">
<label for="ucpassword">Confirm Password:</label>
<input type="password" class="form-control" id="ucpassword" placeholder="Enter password again" name="ucpassword" >
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Why don't you wrap them in a function:
var wrapper = function(){
return checkpass() && check() && validate(this);
}
and then
<form onsubmit="javascript:wrapper()">
Also, you can curry this chain of functions to increase readability but well, the example above must resolve your problem.

How to check if at least one input is completed?

I have this sample:
link
CODE HTML:
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>
CODE JS:
function sendForm() {
var status_form = false;
$(".add-patient input").each(function(){
if($(this).val() == ""){
status_form = true;
}
});
console.log(status_form);
var createdBy = jQuery('#created_by').val();
if( status_form )
{
alert('Fill at least one field');
}else{
alert("now it's ok");
}
}
I want to do a check ... if an input is complete when displaying the message "it; s ok" ... otherwise displaying another message
probably means the code clearly what they want to do.
You can help me with a solution please?
Thanks in advance!
Use .filter to get the length of the input elements having value as ''
Try this:
function sendForm() {
var elem = $(".add-patient input[type='text']");
var count = elem.filter(function() {
return !$(this).val();
}).length;
if (count == elem.length) {
alert('Fill at least one field');
} else {
alert("now it's ok");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>

Adding a node to html page with javascript

This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>

Checking email using js

I have a form that I created and I am trying to check the email field to make sure it's an email. And I only want for people to be able to enter #msu.edu email addresses. I have the script written out to check for the email, but it is not working, and I do not know how to make it to where only a #msu.edu can be used.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkbae()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
</form>
<script language="JavaScript1.2">
var testresults
function checkemail(){
var str=document.validation.emailcheck.value
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults=true
else{
alert("Please input a valid email address!")
testresults=false
}
return (testresults)
}
</script>
<script>
function checkbae(){
if (document.layers||document.getElementById||document.all)
return checkemail()
else
return true
}
</script>
Are you sure that YOU have written the check-script? ;D
In the script you access a field emailcheck which does not exist in the form.
Solutions:
Update
Tested and working.
function checkMail() {
var email = document.validation.email.value.toLowerCase();
var suffix = '#msu.edu';
var result = email.indexOf(suffix, email.length - suffix.length) !== -1;
alert('Valid email found: ' + result);
return result;
}
http://jsfiddle.net/du65V/
Update 2
Using RegEx. Also tested and working.
function checkMail() {
var email = document.validation.email.value.toLowerCase();
var filter = /^([\w-]+(?:\.[\w-]+)*)#msu.edu/i;
var result = filter.test(email);
alert('Valid email found: ' + result);
return result;
}
http://jsfiddle.net/du65V/1/

Categories