Having trouble validating user input with regex with JS - javascript

I'm a complete noob at this stuff.
But my goal here is to accept a certain username and validate it with a certain password.
I've searched and searched all night to no avail so here I am looking for an answer.
My code in html:
<form action="" method="POST" id="loginForm">
<label for="userName" accesskey="F"><br>Username:</label>
<input type="username" name="userName" id="userName">
<label for="password"><br>Password: </label>
<input type="password" name="password" id="password">
<button>Submit</button>
</form>
My code in a seperate javascript file (which is being called by the html file):
function validate(id) {
var guest1User = /guest1/;
var guest2User= /[guest1]/;
var guest1Pass= /[guest2]/;
var guest2Pass= /[guest1]/
var userCheck= document.getElemetnById(userName);
var passCheck= document.getElementById(password);
if (guest1User.test(userCheck.value)) {
if (guest1Pass.test(passCheck.value)) {
return true;
} else {
return false;
}
}
if (guest2User.test(guestCheck.value)) {
if (guest2Pass.test(passCheck.value)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
validate();

Try the following approach:
As per your comment you were wondering how would the js file know that its function has been called.... therefore you need to include the js file in the html file in the following way:
<script type="text/javascript" src="somefile.js"></script>
make sure the path to the somefile.js is correct for example if your file system is like that:
/root/js/
/root/html/
<script type="text/javascript" src="../js/somefile.js"></script>
and your html file is inside the html folder then you refer to the js file as:
function validate(id) {
var guest1User = /guest1/g;
var guest2User= /[guest1]/g;
var guest1Pass= /[guest2]/g;
var guest2Pass= /[guest1]/g;
var userCheck= document.getElementById('userName');
var passCheck=document.getElementById('password');
if (guest1User.test(userCheck.value)) {
console.log("true");
if (guest1Pass.test(passCheck.value)) {
console.log("true");
return true;
} else {
console.log("false");
return false;
}
}
else
{
console.log("false");
return false;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--
<script type="text/javascript" src="../js/somefile.js"></script>
-->
</head>
<body>
<form action="#" method="POST" id="loginForm">
<label for="userName" accesskey="F"><br>Username:</label>
<input type="username" name="userName" id="userName">
<label for="password"><br>Password: </label>
<input type="password" name="password" id="password">
<input type=submit onclick="return validate();" value="submit"/>
</form>
</body>
</html>

Related

Email and mobile number validation on same html5 textbox with button

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);
}

Why my text is printed on page and soon disappears in js

this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!

Javascript validation in php

I'm trying to use javascript to perform client-side verification of input to the following form. The 'firstname' field should contain only alphabetical characters. How can I write the validation function to implement this behaviour?
form.html
<html>
<head>
<script type="text/javascript" src="mainform.js"></script>
</head>
<body>
<form name="mainform" method="post" onSubmit="return validation();" >
firstname <input type="text" name="firstname"><br>
lastname <input type="text" name="lastname"><br>
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
confirm password<input type="password" name="cpassword"><br>
email <input type="email" name="email"><br>
phone no <input type="text" name="phoneno"><br>
<input type="submit" name="submit">
</body>
</html>
form.js
function validation()
{
var fname=document.mainform.firstname;
var letters="/[a-zA-Z]$/";
if(fname.value.match(letters)){
return true;
}
else
{
alert('first name must be alphabets');
fname.focus();
return false;
}
}
function validation()
{
var fname = document.mainform.firstname;
if(/^[a-zA-Z]+$/.test(fname.value)) {
return true;
} else {
alert('first name must be alphabets');
fname.focus();
return false;
}
}
Do not forget to make a check on the server side too for security.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hide</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<style type="text/css">
label input[type="button"]
{
background: #E17698;
}
</style>
<script>
$(document).delegate("#submit","click",function(e)
{
var name = $("#fname").val();
var hasError = false;
var searchReg = /^[a-zA-Z ]+$/;
if(name == '') {
$("#txtt").after('<span class="error" style="color:red;"> *Fill Name Box</span>');
hasError = true;
} else if(!searchReg.test(name)) {
$("#txtt").after('<span class="error" style="color:red;"> **Enter Vaild Name.</span>');
hasError = true;
}else if(searchReg.test(name)) {
$("#txtt").after('<span class="error" style="color:white;"> Vaild Name</span>');
}
if(hasError == true) {
return false
}
});
</script>
</head>
<body>
<form name="mainform" method="post">
firstname <input type="text" name="firstname" id='fname'><label id="txtt"></label><br>
lastname <input type="text" name="lastname"><br>
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
confirm password<input type="password" name="cpassword"><br>
email <input type="email" name="email"><br>
phone no <input type="text" name="phoneno"><br>
<input type="submit" name="submit" id='submit'>
</form>
</body>
</html>

js and jquery validation not working

my html code is below
<script src="js/validate.js"></script>
<label>FIRST NAME:</label>
</td>
<td>
<input type="text" class="firstname" id="firstname" onKeyUp="firstname()" />
</td>
<td>
<label id="fn"></label>
and my js code is below
function firstname()
{
var nname=document.getElementById("firstname").value;
var l=nname.length > 3 ;
if( !l)
{
producePrompt("firstname should not be less than 4 characters","fn","red");
return false;
}
else
if(!nname.match(/^[a-zA-Z\s]*$/))
{
producePrompt("incorrect name","fn","red");
return false;
}
else
{
producePrompt("correct","fn","green");
return true;
}
}
function producePrompt(message,promptlocation,color)
{
document.getElementById(promptlocation).innerHTML= message;
document.getElementById(promptlocation).style.color= color;
}
but my code is not showing the messages or does not validate it properly
the js is under a file named validate.js and html is in index.html
i tried both types (,) to include the js file but no validation is taking place
try this , works fine for me (validation works) :
js :
function checkinput()
{
var nname=document.getElementById("firstname").value;
var l=nname.length > 3 ;
if(!l)
{
console.log("firstname should not be less than 4 characters","fn","red");
return false;
}
else
if(!nname.match(/^[a-zA-Z\s]*$/))
{
console.log("incorrect name","fn","red");
return false;
}
else
{
console.log("correct","fn","green");
return true;
}
}
html:
<form>
<label>FIRST NAME:</label> <input type="text" class="firstname" id="firstname" onblur="checkinput()" />
</form>
<body>
// all your html contents
// load the scripts here
<script src="js/validate.js"></script>
</body>
OR
<body>
// all your html contents
<script>
// javascript contents
</script>
</body>

Javascript validation error

I have written the following code in html and the javascript file is also embedded below
<!DOCTYPE html>
<meta charset="utf-8">
<HTML>
<head>
<link rel="stylesheet" href="admin.css"/>
<script type="text/javascript" src="common.js"></script>
</head>
<BODY>
<div class="adminnav" id="adminnav">
<ul>
<li>Insert
<ul>
<li>Insert Course</li>
<li>Insert Student</li>
<li>Insert Teacher</li>
<li>Insert Subject</li>
</ul>
</li>
</ul>
</div>
<div class="addcourse" >
<form name="course" onSubmit='return validcourse()' method="POST">
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:<input type="text" name="cd"/>
<br>
Course Id:<input name="cid" type="text" /><br>
<input type="submit" value="submit" name="submit"><input type="reset" name="coursereset">
</form>
</div>
</BODY>
</HTML>
common.js
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
}
}
}
}
}
function course_name_valid(course_name)
{
var letters=/^[A-Za-z]+$/;
if(course_name.value.match(letters))
{
return true;
}
else
{
alert("Course name must have alphabets only");
course_name.focus();
return false;
}
}
function course_duration_valid(course_duration)
{
var letters=/^[1-9]+$/;
if(cd.value.match(letters))
{
return true;
}
else
{
alert("Course Duration can have numbers only");
course_duration.focus();
retun false;
}
}
function course_id_valid(course_id)
{
var letters=/^[0-9a-zA-z]+$/;
if(course_id.value.match(letters))
{
return true;
}
else
{
alert('Course ID must have character and numeric values only');
course_id.focus();
return false;
}
}
My problem is that nothing is happening no error messages are given.
Error messages are given only for course name but not for course duration and course id?
Here is a link to jsfiddle http://jsfiddle.net/amolkarale/aTfq6/1/
You are not returning anything from validcourse. Add a return true; and return false; in there, to either let the submission continue or stop the submission from happening:
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
return true;
}
}
}
}
return false;
}
Looks like you have a syntax error in your third functioncourse_duration_valid(course_duration)
retrun false;
should be:
return false;
Okay, so I got your stuff to work. Here are the changes needed:
First, object references need to be cleaner in your DOM
var course_name=document.getElementById("cname");
var course_duration=document.getElementById("cd");
var course_id=document.getElementById("cid");
As you can see, the elements need to have their individual ids.
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:
<input type="text" name="cd" id="cd"/><br>
Course Id:
<input name="cid" type="text" id="cid" /><br>
Finally, the retrun needed to be corrected, as already pointed out by #Steve

Categories