Make form validation via custom attributes - javascript

please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>

Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.

You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>

Related

How to determine whether a form is valid and display a popup window depdnding on whether is is valid or not?

I'm trying to create a form where the user fills out their details, the form currently doesn't send if one of the fields has no input in it because I have added in a "required" into each of the tags to create the field. I have written some JavaScript to open a popup if the form is valid but it isn't working, the form submits to my PHP database but the pop up window doesn't appear. Any thoughts? Here is my current JavaScript.
Code for the form fields -
label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..." required>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..." required>
<label for="phonenumber">Phone Number</label>
<input type="text" id="phonenumber" name="phonenumber" placeholder="The best number to contact you on..." required>
Code to call the script -
<button onclick="myFunction()">Submit</button>
JavaScript validation
<script>
function validateForm() {
var x = document.forms["fname"].value;
var y = document.forms["lname"].value;
var p = document.forms["phonenumber"].value;
if ([x == "", y =="", p ==""]); {
alert("Name must be filled out");
return false;
}
}
function myFunction() {
if (x == "") {
return false;
}
else {
alert("Thank you for making an enquiry, a member of our team will be in contact with you soon.");
}
}
Try Code Below
<script>
function validateForm() {
var x = document.forms["Forms"]["fname"].value;
var y = document.forms["Forms"]["lname"].value;
var p = document.forms["Forms"]["phonenumber"].value;
if (x == "" && y =="" && p ==""); {
alert("Name must be filled out");
return false;
}
else
{
return true ;
}
}
<form name="Forms" onSubmit="return validateForm() "><input type="text" name="fname" /><input type="text" name="lname" /><input type="text" name="phonenumber" /></form>
or you can simply use required in every input

Form Validation not responding correctly

I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.

Validation not working perfectly

This is my code:
function email() {
var reg = new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam = document.registration.email.value;
var res = nam.match(reg);
if (res) {
alert("enter valid email");
document.registration.email.focus();
} else {
document.registration.password.focus();
}
} else {
document.registration.email.focus();
}
}
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" onblur="email()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
The validation is not working and thus the alert in if condition is not showing. Can anyone help me to achieve this type of validation.
Thanks in advance
Well... Assuming you are trying to do some input validation for your form I suggest reading a bit regarding email validation regex. Then use something like:
https://www.regextester.com/19
Then I think your if statement is flawed. I think you meant that if the email matchs the regular expression if should focus on the password field. if the email is not empty and is invalid if should present an alert. if the email is empty it should focus on the email. I did a quick cleanup and i think the code should look something like(untested code for illustration only):
function validateInput() {
var email= new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var inputValue=document.registration.email.value;
if(inputValue.match(email)) {
document.registration.password.focus();
} else if (inputValue.length > 0) {
alert("enter valid email");
document.registration.email.focus();
} else {
document.registration.email.focus();
}
}
email is a reserved keyword in javascript. first rename your function email to test or whatever you want. second thing you have extra else in your code.
There is a couple errors in your javascript - syntax and dom api.
If you want to do manual validation, here is an example in a fiddle that would work.
https://jsfiddle.net/xb4qrvmy/
function validate_email()
{
var reg=new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam=document.forms["registration"].email.value;
var res=nam.match(reg);
if(!res && nam.length)
{
// I would advice against using alert.
alert("enter valid email");
document.registration.email.focus();
// You want to somehow reset the displaying of the error.
document.forms["registration"].email.value = ''
} else if (res) {
document.registration.password.focus();
}
}
Since You are using html 5 you don't need to write your own validation for email just use
HTML5 has inbuilt validation check for email.
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="email" name="email" placeholder="Email" onblur="email()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
But in case you want to use your function anyways use it as :
<html>
<head>
<script>
function emails()
{
var reg=new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam=document.registration.email.value;
if(!new RegExp(reg).test(nam))
{
alert(document.registration.email);
document.registration.password.focus();
} else {
document.registration.password.focus();
}
}
</script>
</head>
<body>
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" onblur="javascript:emails()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
</body>
function validate()
{
var x = document.forms["myform"]["email"].value;
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;
}
}
</script>

Regular Expressions, Length check in Javascript

I want to validate my form now, and I wrote some code, it's working perfectly for length constraints but I want to use Regular Expression to filter the values of each element.
I found from a forum, these Regular Expressions:
for Full Name: var regex = /^[a-zA-Z ]$/;
for Phone: var regexPhone= /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
I guess the HTML5 (input:type email) is enough for email validation
Also I want to do this with the name, that when I type the full name, the first letters change to uppercase letters. For example--> input="john smith", changes to "John Smith".
This is my code:
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if(pedio.id.indexOf("Name")!=-1){
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if(pedio.id.indexOf("Phone")!=-1){
if (pedio.value.length!=10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail"autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br>
-If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>
Option 1: You can use text-transform: capitalize CSS property which will automatically do the task of converting a name from john cena to John Cena.
Check the example below in the CSS
Option 2:
I have added a new input called Nick name which uses javascript to do the same task.
I have used keyup handler to capture the all key input event so that we can execute a piece of code which will do the job on capitalizing the name.
The result is simple string manipulation which splits the name with <space-character> and converts the first character to uppercase and joins the same with rest of the string.
document.addEventListener("DOMContentLoaded", function() {
document.querySelector("#NickName").addEventListener("keyup", capitalizeName);
});
function capitalizeName() {
if (!this.value) return;
var aNewName = this.value.split(" ").map(function(name) {
return name.charAt(0).toUpperCase() + name.substring(1);
});
this.value = aNewName.join(" ");
}
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if (pedio.id.indexOf("Name") != -1) {
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if (pedio.id.indexOf("Phone") != -1) {
if (pedio.value.length != 10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
#Name {
text-transform: capitalize;
}
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="text" id="NickName" name="NickName" placeholder="*Nick name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail" autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br> -If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>
Hint:
The RegExp object has a method test which when given a string argument returns true if there was at least one match in the str or false. MDN Documentation
Used as /regexp/.test(str). You already have code that tests for length. You want to test for the length AND for this regex.
When you want to capitalize the first letter of each word, that is called Title Case. There's an excellent answer here for that part of your question

Failed to validate email address with regular expression

I would like to run my page to test out whether my validation works. However, it does not work with email address. I have added regular expression for email address. It doesn't validate fully.
I entered a#live without typing .com it able to accept it. I assume this is because i type input="email" Correct me wrong. Is it due to the wrong regular expression or maybe the way I placed my code?
javascript
function validate(){
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var emailReg = '/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/';
var re = /^[\w ]+$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(email=="")
{
alert('Please fill in email fields');
return false;
}
else if(fname=="")
{
alert('Please fill in first name fields');
return false;
}
else if(lname=="")
{
alert('Please fill in last name fields');
return false;
}
return true;
}
register.php
<form name="registrationForm" method="post" id="registrationForm" class="registrationForm" action="processRegister.php" onclick="validate">
<div class='input1'>
<span id="emailAddress-label" class="help"></span>
<input class="regemailaddr" id="emailAddress" name="emailAddress" type="email" placeholder="Email Address " value="" required>
</div>
<br>
<span id="fname-label" style="margin-bottom:" class="help"></span>
<input id="fname" name="fname" type="text" placeholder="First Name " class="fname" value="" required>
<span id="lname-label" class="help"></span> <input id="lname" name="lname" type="text" placeholder="Last Name " class="lname" value="<?php echo $user_profile["lname"]; ?>" required>
<br>
<button class="greybtn" type="submit" id="submitButton">Submit</button>
<button class="cancelbtn" type="button" id="cancelButton" onclick="window.location='#';return false;">Cancel</button>
</form>
You have defined a regular expression
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
but you do not test against it
var isEmail = emailReg.test(email);

Categories

Resources