I want to make validation for my email input text and phone number input text. In the email, I want to put only '#gmail.com' and phone number the user only input number in the form. I already use JavaScript but it doesn't work.
function validation() {
var mailformat = /^\w+([\.-]?\w+)*#gmail.com*(\.\w{2,3})+$/;
var phoneno = /^\d{10}$/;
if (document.getElementById("name").value.length == 0) {
document.getElementById("message").innerHTML = "<em> You did not enter your name </em>";
return false;
}
if (document.getElementById("email").value.match(mailformat) != mailformat) {
document.getElementById("message1").innerHTML = "<em> please enter </em>";
return false;
}
if (document.getElementById("postcode").value.length < 4) {
document.getElementById("message2").innerHTML = "<em> Minimum is 4 Characters for Postcode </em>";
return false;
}
if (document.getElementById("phone").value.length == 0) {
document.getElementById("message3").innerHTML = "<em> You did not enter your phone </em>";
return false;
}
return true;
}
<form class="form-horizontal container" method="POST" action="#" onsubmit="return validation()">
<!-- Name Validation input -->
<div class="form-group">
<label class="control-label col-md-2 label1" style="text-align: left;" for="name">Name:</label>
<div class="col-md-5">
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
<span id="message"></span>
</div>
</div>
<!-- Email Validation input -->
<div class="form-group">
<label class="control-label col-sm-2 label1" style="text-align: left;" for="email">Email:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="email" placeholder="Enter Email" name="email">
<span id="message1"></span>
</div>
</div>
<!-- Postcode Validation Input -->
<div class="form-group">
<label class="control-label col-sm-2 label1" style="text-align: left;" for="postcode">Postcode:</label>
<div class="col-sm-5">
<input type="text" oninput="this.value=this.value.replace(/[^0-9]/g,'');" class="form-control" id="postcode" placeholder="Enter Postcode" name="postcode">
<span id="message2"></span>
</div>
</div>
<!-- Phone Validation Input -->
<div class="form-group">
<label class="control-label col-sm-2 label1" style="text-align: left;" for="phone">Phone:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="phone" placeholder="Enter Phone" name="phone">
<span id="message3"></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit the query</button> <button type="reset" class="btn btn-default button3"> Reset</button>
</div>
</form>
Use regex like this
var mailformat = /^\w+([\.-]?\w+)*[#gmail.com]*(\.\w{2,3})+$/;
var email_val = document.getElementById("email").value;
if(!email_val.match(mailformat)){
document.getElementById("message1").innerHTML = "<em> please enter email dsfsdfa</em>";
return false;
}
You can make it more better, like apply validation for empty field before this too.
Match returns an array if it is matched. So comparing an array to a regular expression is wrong. You can use a truthy check
if(!document.getElementById("email").value.match(mailformat)) {
or use .test() instead.
You could look at this website which shows basic javascript code for validation
https://getcodingkids.com/mission/mission-2/
Where did you get your email validation regex? The pattern /^\w+([\.-]?\w+)*#gmail.com*(\.\w{2,3})+$/ matches (inefficiently) one or more words joined by periods or hyphens, followed by #gmail,followed by any character at all, followed by co, followed by any number of ms including zero, followed by at least one sequence of period plus two or three more letters. So it won't match anything ending in #gmail.com, but will match something ending in #gmail.co.uk or similar. So even if you fix the validation logic in the code, this regex won't match against any email address ending in gmail.com, which it sounds like you want to do..
Related
I was trying to write a simple Vanilla JS function which would check if user has left any form fields empty and if that's the case, then alert the user. Unfortunately, it doesn't quite work and I don't know why.
As, you can see it says "undefined can't be left empty".
Here's the JS Code:
var username= document.getElementById("UsernameInput");
var email= document.getElementById("EmailInput");
var pass= document.getElementById("PasswordInput");
var confirmPass= document.getElementById("ConfirmPasswordInput");
var form= document.querySelector(".registration-form");
// Function for checking empty input
function checkEmpty(inputArr){
for(i=0;i<inputArr.length;i++){
if(inputArr[i].value.trim()==='')
var stringified= JSON.stringify(inputArr[i]);
alert(`${stringified} can't be left empty`);
console.log(inputArr[i]);
break;
}
}
form.addEventListener("submit", function(e){
if(checkEmpty([username,email,pass,confirmPass]));
e.preventDefault();
})
So, why is the "stringified" variable undefined? (I'm using JSON.stringify because when I was not doing that it was returning [object object]).
Here's the HTML for the form:
<form action="#" class="registration-form ">
<div class="row ">
<div class="six columns ">
<label for="username">Your username (has to be unique)</label>
<input class="u-full-width" type="text" placeholder="redditStar" id="UsernameInput" name="username">
</div>
</div>
<div class="row">
<div class="six columns">
<label for="email">Your email</label>
<input class="u-full-width" type="email" placeholder="test#emailcom" id="EmailInput" name="email">
</div>
</div>
<div class="row">
<div class="six columns">
<label for="password">Your password</label>
<input class="u-full-width" type="password" placeholder="Enter a strong password" id="PasswordInput" name="password">
</div>
</div>
<div class="row">
<div class="six columns">
<label for="confirm-password">Confirm your Password</label>
<input class="u-full-width" type="password" placeholder="Confirm password.." id="ConfirmPasswordInput" name="passwordConfirm">
</div>
</div>
<input class="button-primary submitRegister" type="submit" value="Submit">
</form>
The problem is your if statement in the for.
for(i=0;i<inputArr.length;i++){
if(inputArr[i].value.trim()==='')
var stringified= JSON.stringify(inputArr[i]);
alert(`${stringified} can't be left empty`);
console.log(inputArr[i]);
break;
}
Following javascript's indentation rules when your if lacks curly braces, if expression is true only the next line is run. If it's false, it skips the next line. So, when that if is false, it jumps to alert(``${stringified} can't be left empty``); which stringified is undefined since it was not defined on the line before.
So im making a sign up form and in the sign up form i need the user to put input in 1 of 2 text fields, i already have code that requires text for one field however i need to expand on this code for it to be able to check over 2 fields.
Below is an example of the code with the corresponding HTML that i have.
The fields that i want the new code to check are called 'ctt' and 'bcn'.
Im normally bad at explaining so if anyone needs me to explain any further in what im trying to do dont hesitate to ask.
{
var username = document.querySelector('input[name="username"]');
username.setCustomValidity('Please enter a user name, minimum length of 2 characters, maximum 32 characters');
username.addEventListener('input', function () {
if (this.value.trim() === '') {
this.setCustomValidity('Please enter a user name, minimum length of 2 characters, maximum 32 characters');
}
else {
this.setCustomValidity('');
}
}, false);
username.addEventListener('invalid', function () {
if (this.value.trim() !== '') {
this.setCustomValidity("Please enter a user name, minimum length of 2 characters, maximum 32 characters");
}
}, false);
}
<div class="group">
<div class="col-1">
<label for="username">Username*</label>
</div>
<div class="col-2">
<input type="text" name="username" id="username" minlength="2" maxlength="32" placeholder="username" required/>
<span class="validity"></span>
</div>
</div>
The input field i want the code to read will be below
<!-- CTT Number -->
<div class="group">
<div class="col-1">
<label for="ctt">CTT Number</label>
</div>
<div class="col-2">
<input type="text" id="ctt" name="ctt" pattern="[0-9]{8}" maxlength="8" placeholder="CTT Number" />
<span class="validity"></span>
</div>
</div>
<!-- BC Number -->
<div class="group">
<div class="col-1">
<label for="bcnum">BC Number</label>
</div>
<div class="col-2">
<input type="text" id="bcn" name="bcn" pattern="[0-9]{8}" maxlength="8" placeholder="BC Number" />
<span class="validity"></span>
</div>
</div>
I have created a contact (4 input text) form and I want if user doesn't text in anyone of input a text message will appear above each input.
Contact From:
<form class="form-horizontal" method="post" action="#" name="form" onsubmit="return validation();">
<fieldset>
<div><h2 style="font-family: Myriad Pro;color:#7f8c8c">form</h2></div>
<div class="form-group">
<div class="col-sm-8">
<input id="fname" name="name" type="text" placeholder="Όνομα" class="form-control">
<div id="error1" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input id="lname" name="surname" type="text" placeholder="Επώνυμο" class="form-control">
<div id="error2" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 ">
<input id="email" name="email" type="email" placeholder="E-mail" class="form-control">
<div id="error3" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 ">
<textarea id="message" name="message" type="text" placeholder="Το σχόλιο σας.." columns="7" rows="7" class="form-control" style="background-color:#e5e6e6;" required=""></textarea>
<div id="error4" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 text-center">
<button type="submit" class="btn btn-primary btn-block" id="label" >SEND</button>
</div>
</div>
</fieldset>
</form>
And the script I use:
function validation(){
if (document.form.name.value == "") {
document.getElementById('error1').innerHTML="*Error Msg1 ";
}else if (document.form.surname.value == "") {
document.getElementById('error2').innerHTML="*Error Msg2 ";
}else if (document.form.email.value == "") {
document.getElementById('error3').innerHTML="*Error Msg3 ";
}else if (document.form.message.value == "") {
document.getElementById('error4').innerHTML="*Error Msg4 ";
}
return false;
}
My issue is that if for example the user doesn't fill his name(error message displayed below the text field) BUT then if he text his name the error message IS still displayed.How can I solve this?
There is an example here: Fiddle
I would suggest that you clear the error message at the start of the validation again:
function validation(){
document.getElementById('error1').innerHTML=""
document.getElementById('error2').innerHTML=""
document.getElementById('error3').innerHTML=""
document.getElementById('error4').innerHTML=""
//Your validation code below:
...
}
This way whenever the input validates, all of the error messages will be cleared and evaluated again.
You might want to consider storing the labels at the start of the function in a field so you have easy access to them later. This should help with readability as well. For example:
function validation(){
var errorMessage1 = document.getElementById('error1');
//Access the label using your new variable:
errorMessage1.innerHTML = "Your value here"
...
On keyup event lets try resetting the error message
document.form.name.addEventListener("keyup", function(){
document.getElementById('error1').innerHTML = '';
});
Want to set phone-number to 10 digits, How can I do this using Angular js.
This is what I have tried:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required &&
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.password.$error.minlength ||
registration.password.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
</div>
</div>
</form>
But I am not getting the validation error.
Try this:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required ||
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.phone.$error.minlength ||
registration.phone.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
Check this answer
Basically you can create a regex to fulfil your needs and then assign that pattern to your input field.
Or for a more direct approach:
<input type="number" require ng-pattern="<your regex here>">
More info # angular docs here and here (built-in validators)
You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.
function form($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div ng-app ng-controller="form">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>
<input type="submit" value="submit"/>
</form>
</div>
You can also use ng-pattern and I feel that will be a best practice. Similarly try to use ng-message. Please look the ng-pattern attribute on the following html. The code snippet is partial but hope you understand it.
angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
$scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number" class="form-control" ng-pattern="ph_numbr" id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
<div class="help-block" ng-messages="registration.phone.$error">
<p ng-message="required">Phone number is required.</p>
<p ng-message="pattern">Phone number is invalid.</p>
</div>
</div>
</div>
</form>
use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also.
on npm: https://www.npmjs.com/package/ng-intl-tel-input
more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/
An even cleaner and more professional look I have found is to use AngularUI Mask. Very simple to implement and the mask can be customized for other inputs as well. Then a simple required validation is all you need.
https://angular-ui.github.io/
<form name = "numberForm">
<div>
<input type="number"
placeholder = "Enter your phonenumber"
class = "formcontroll"
name = "numbers"
ng-minlength = "10"
ng-maxlength = "10"
ng-model="phno" required/>
<p ng-show = "numberForm.numbers.$error.required ||
numberForm.numbers.$error.number">
Valid phone number is required</p>
<p ng-show = "((numberForm.numbers.$error.minlength ||
numberForm.numbers.$error.maxlength)
&& numberForm.numbers.$dirty)">
Phone number should be 10 digits</p><br><br>
</div>
</form>
Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.
<form name="phoneNumber">
<label for="numCell" class="text-strong">Phone number</label>
<input id="numCell" type="text" name="inputCelular" ng-model="phoneNumber"
class="form-control" required ng-pattern="/^[0-9]{10,10}$/"></input>
<div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
<p> write a phone number</p>
</div>
<button id="button" class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>
Also you can use another complex patern like
^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$
, for more complex phone numbers
<div ng-class="{'has-error': userForm.mobileno.$error.pattern ,'has-success': userForm.mobileno.$valid}">
<input type="text" name="mobileno" ng-model="mobileno" ng-pattern="/^[7-9][0-9]{9}$/" required>
Here "userForm" is my form name.
I have started to write the validation for user registration. This form is so users can register on the site, however I'm having issues with how to properly write validation for each field.
so far:
<div id="content">
<div class="ic"></div>
<div class="inner">
<div class="container_12">
<div class="wrapper">
<div class="grid_12">
</div>
</div>
<div class="wrapper">
<div class="grid_12">
<h2 class="h-pad1">Open an Account with Us</h2>
<form action="" id="validate" class="form" method="POST">
<fieldset>
<div class="formRow">
<label for="login">Username:</label>
<div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Password:</label>
<div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Repeat Password:</label>
<div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Email:</label>
<div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div>
<div class="clear"></div>
</div>
What would be the proper code to add? Thank you.
Your most important task is to learn how to use document.getElementById() if your going to be using regular javascript. With that function you can grab the value in the different fields and check what is stored in them.
I would have a highlevel function validateRegistrationForm() that calls functions for validating each field. For example
function validateRegistrationForm(){
if(!validateEmailField()) // Invalid email format
return;
if(!validatePasswordField()) // Invalid password length
return;
if(validateUserNameField()) // invalide characters in email
return;
.
.
etc.
}
function validateEmailField(){
var x=document.getElementById("email").value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
errorPopup("Not a valid e-mail address");
return false;
}
if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored.
return true;
return isEmailUnique(); // return true if the email is unique
}
You can have something like:
function validate()
{
var uName = document.getElementById('username');
if(uName == '' or uName=' ')
{
// do something
}
repeat for other elements.
.
.
.
.
// in the end, you can return true; if all validation condition meet or else return false;
}