Name,Email Validation - javascript

I'm looking for code that validates the Name and Email input's on <Form onsubmit="return validate();">
I want that username has only A-Z,a-z and must have an underscore_, email should have an #. How can i do it with jQuery?
Form(example):
<html>
<head>
<title>TEST</title>
</head>
<body>
<form action="..." method="POST" onSubmit="return Check()" >
<input type="text" id="name" placeholder="Please enter your Name. (Must have underscore)" required>
<input type="text" id="email" placeholder="E-Mail">
<input type="submit" value="submit">
</form>
</body>
</html>
EDIT I've tried:
<script type="text/javascript">
jQuery(document).ready(function($){
$('[name="submit"]').click(function(e){
var name = document.getElementById("name").value;
if(re = /[a-zA-Z]*_[a-zA-Z]*/;) {
$(".name").addClass("error");
return false;
} else {
$(".name").removeClass("error");
$(".name").addClass("success");
return true;
}
});
});
Thanks!

For a valid email address:
Validate email address in JavaScript?
For your username is the same but your regex should be something like this:
re = /^[a-zA-Z]*_[a-zA-Z]*$/; //this always needs an underscore to be valid.
Just in case, this is the regex to accept anything az AZ and _ and nothing, it depends on your requirements:
re = /^[a-zA-Z_]*$/;
re = /^[a-zA-Z_]{3,}$/; //3 or more chars
To test your regex:
re = /^[a-zA-Z_]*$/;
return re.test('any_string_to_test'); //it returns true if your string is valid

Using regex with jquery:
Pass a string to RegExp or create a regex using the // syntax call
regex.test(string) not string.test(regex)
In your code:
$(".name").on('keyup', function(e)
{
var name = $(this).val();
if(new RegExp(/^[a-zA-Z_]+$/i).test(name)) // or with quotes -> new RegExp("^[a-zA-Z_]+$", 'i')
$(this).addClass("error");
else
$(this).switchClass("error", "success", 1000, "easeInOutQuad");
e.preventDefault();
e.stopPropagation(); // to avoid sending form when syntax is wrong
});
And for email input, the following regex can do the job :
/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
Or..
To put a little bit of modernity, you can use html5 email field type
<input type="email" id="email">

Now using the advanced feature of HTML5 it's eaiser, you can simply do the validation as follow:
<form action="" method="">
<!-- Name containing only letters or _ -->
Name: <input type="text" name="name" pattern="[a-zA-Z][[A-Za-z_]+" />
<!-- using type email, will validate the email format for you-->
Email: <input type="email" id="email" />
<input type="submit" value="Submit">
</form>
Check HERE for more form validation features of HTML5.

#Polak i tried so, if i understand what you mean :x Sorry i'm new with javascript.
<script type="text/javascript">
jQuery(document).ready(function($){
$('[name="submit"]').click(function(e){
var name = document.getElementById("display_name").value;
re = /[a-zA-Z]*_[a-zA-Z]*/;
if (re.test(name) {
//Things to do when the entry is valid.
$(".NameCheck").removeClass("name_error");
$(".NameCheck").addClass("name_success");
return true;
} else {
//Things to do when the user name is not valid.
$(".NameCheck").addClass("name_error");
return false;
});
});
});

Related

Why is my HTML file unable to use the JavaScript file that I have linked?

JavaScript file is not used in the HTML file despite linking it
I am unable to use the JavaScript file and validate my HTML form. I am wondering if the issue is the linking of the src directory is wrong or could it be that I am missing something in my JavaScript code.
<html>
<head>
<title>Registration Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/validation.js" type="text/javascript">
</script>
</head>
<body>
<form action="validate" method="post" name="register">
Full Name: <input type="text" name="name" required/><br/> Email Address: <input type="email" name="email" required/><br/> Address Line 1: <input type="text" name="address1" required/><br/> Address Line 2: <input type="text" name="address2" /><br/> Postal Code: <input type="number" name="postal" required/><br/> Mobile Number: <input type="number" name="mobile" required/><br/> Password: <input type="password" name="password" required/><br/> Confirm Password: <input type="password" name="cfpassword"
required/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
function validateForm() {
//Use a regular expression to check for the pattern of the password
var regexPass = "^[0-9]{6}[a-zA-Z]{1}$";
var regexMobile = "^[0-9]{8}$";
var regexPost = "^[0-9]{6}$";
//Retrieve the VALUE from the "password" field found in the "register" form
var password1 = document.forms["register"]["password"].value;
var password2 = document.forms["register"]["cfpassword"].value;
var postalcode = document.forms["register"]["postal"].value;
if (matchPost === null) {
alert("The postal code given in the correct format. Please ensure
that is contains exactly 6 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
if (matchMobile === null) {
alert("The mobile number given in the correct format. Please ensure
that is contains exactly 8 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
// If password not entered
if (password1 == '')
alert("Please enter Password");
// If confirm password not entered
else if (password2 == '')
alert("Please enter confirm password");
// If Not same return False.
else if (password1 != password2) {
alert("\nPassword did not match: Please try again...")
return false;
}
// If same return True.
else {
return true
}
}
If your JS folder is in the same directory as your html file this code should work. Write a simple alert('ahoy') function in your JS file and reload your html to verify if your JS file is loaded or not.

Html Form Unable to Validate Inputs using JavaScript

I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

JavaScript validation file not working: "ReferenceError: validateForm is not defined" (html linked)

(edit: code updated)
I am running into an error, when trying to clientside-validate with JavaScript that the user has filled in the forms correctly in the Register part of my HTML form.
The HTML and JS file are pretty straightforward:
(Fiddle)
JavaScript and HTML:
function validateForm() {
var name = document.getElementById('username').value;
var email = document.getElementById('email').value;
if (name == null || name == "" || checkIfSpaceOnly(name) == false) {
return false;
}
else if (email == null || email == "" || validateEmail(email) == false){
return false;
}
else
return true;
}
//other methods used in validateForm:
function checkIfSpaceOnly(input) {
var re = /\S/;
return re.test(input);
}
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);
}
window.onload = function()
{
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener("click", validateForm);
}
<!DOCTYPE html5>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="design.css">
</head>
<div class = "body1">
<div class = "forms" id="forms">
<h2>Log in</h2>
<form name='loginform' action='login.php' method='POST'>
<input type='email' name='email' placeholder="Email" ><br>
<input type='password' name='password' placeholder="Password" ><br><br>
<input type='submit' value='Log in'><br><br>
</form>
<hr>
<br><h2>Register</h2>
<form onsubmit="" name="register" action="register.php" method="POST" onsubmit="return validateForm()">
<input type="text" name="username" class="form-control" placeholder="Username" id="username"><br>
<input type="email" name="email" class="form-control" placeholder="Email" id="email"/><br>
<input type="password" name="password" class="form-control" placeholder="Passwoord"><br>
<br>
<input type="submit" name="submit" id="submit" value="Create user">
</form>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</html>
So the problem is, it's like the JS file isn't used at all by the HTML file. The form gladly registers any user, no matter if they fulfill the JavaScript file's if conditions or not.
I checked the console, and it says (when the user has been registered), "ReferenceError: validateForm is not defined".
Except checking that the file directories are correct of course, I have searched and read about both general HTML JS form validation Errors, 20-something "similar question" on here, and that specific ReferenceError. I've changed values, names, moved code parts around.... but I can't seem to find the problem and don't know what to do, although it feels like it's just a simple mistake somewhere in the code.
You have 3 problems
Your fiddle is setup incorrectly; all the code is wrapped in an onload which means your validateForm method is not accessible from HTML markup
You have 2 onsubmit attributes in the form - the second contains what it should contain but is being ignored because of the first
You assign the event handler both in markup and in code. Choose one, stick with it.
When you fix these 3 problems, it works as expected and does not submit the form if anything goes wrong (ie, false is returned from validateForm)
https://jsfiddle.net/spwx1rfd/7/
Please check the if condition, you have made a mistake.
Wrong code
if (uName == "") || checkIfSpaceOnly(uName) == false) {
return false;
}
Right code
if (uName == "" || checkIfSpaceOnly(uName) == false) {
return false;
}

js validation of not null field

I have done a login page. I want my js validateForm()function to alert a user if they have left out the username or password. This is the code I have got at the moment.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("Please enter username");
return false;
}
}
</script>
</head>
<div class="users form">
<br>
<form name="myform" action="Employees/login" onsubmit="return validateForm()" method="post" >
<?php
if (isset($error)) {
echo "<p style='color:red;font-size: 20px''>Username or Password is invalid. Please try again.</p>";
}?>
<p>Enter Username:
<input type="text" name="username" placeholder="username" style="height: 25px;width: 160px;"/></p>
<br><br>
<p>Enter Password:
<input type="password" name="password" placeholder="password" style="height: 25px;width: 160px;"/></p>
<br>
<input type="submit" style="height:35px;width:100px;font-size: 18px; align:center;" value="Sign in">
</form>
</div>
At the moment it is not working, and I think the problem is with the code line "var x=document.forms["myForm"]["username"].value;" Can someone please help?
The issue is forms["myForm"], you used an uppercase F, when actually your form name is all lowercase so it should be:
var x=document.forms["myform"]["username"].value;
// ^ lowercase
Not part of the problem, but you might prefer to use unobtrusive JavaScript to set the onsubmit handler instead of in the HTML attribute:
window.onload = function(){
document.forms["myform"].onsubmit = validateForm;
};
Now, in validateForm you can use this instead of finding the form manually.
function validateForm()
{
var x = this["username"].value;
...
}

Why my form doesn't validate correctly?

I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)

Categories